为什么我不能在单个服务器请求中插入带有外键的记录?
我正在尝试使用外键进行简单插入,但似乎我需要为每个记录插入使用db.SaveChanges()
。 如何在此程序结束时只使用一个db.SaveChanges()
?
public static void Test() { using (var entities = new DBEntities()) { var sale = new SalesFeed { SaleName = "Stuff...", }; entities.AddToSalesFeedSet(sale); var phone = new CustomerPhone { CreationDate = DateTime.UtcNow, sales_feeds = sale }; entities.AddToCustomerPhoneSet(phone); entities.SaveChanges(); } }
运行上面的代码后,我得到以下exception:
System.Data.UpdateException:更新条目时发生错误。 有关详细信息,请参阅InnerException。 指定的值不是有效常量类型的实例参数名称:value。
编辑:更改了示例代码并添加了返回的exception。
显然使用UNSIGNED BIGINT
会导致此问题。 当我切换到SIGNED BIGINT
一切都按预期工作。
我试图以“正确的方式”做到这一点:
替代文字https://sofzh.miximages.com/c%23/mcw5co.png
然后我编写了这个小测试应用程序来扫描目录,将目录及其所有文件存储在两个表中:
static void Main(string[] args) { string directoryName = args[0]; if(!Directory.Exists(directoryName)) { Console.WriteLine("ERROR: Directory '{0}' does not exist!", directoryName); return; } using (testEntities entities = new testEntities()) { StoredDir dir = new StoredDir{ DirName = directoryName }; entities.AddToStoredDirSet(dir); foreach (string filename in Directory.GetFiles(directoryName)) { StoredFile stFile = new StoredFile { FileName = Path.GetFileName(filename), Directory = dir }; entities.AddToStoredFileSet(stFile); } try { entities.SaveChanges(); } catch(Exception exc) { string message = exc.GetType().FullName + ": " + exc.Message; } } }
正如你所看到的,我在最后只有一次调用.SaveChanges()
– 这就像一个魅力,一切都如预期的那样。
关于你的方法的一些事情必须搞砸EF系统……
上述就是C#学习教程:为什么我不能在单个服务器请求中插入带有外键的记录?分享的全部内容,如果对大家有所用处且需要了解更多关于C#学习教程,希望大家多多关注—计算机技术网(www.ctvol.com)!
本文来自网络收集,不代表计算机技术网立场,如涉及侵权请联系管理员删除。
ctvol管理联系方式QQ:251552304
本文章地址:https://www.ctvol.com/cdevelopment/983787.html