为什么我不能在单个服务器请求中插入带有外键的记录?

我正在尝试使用外键进行简单插入,但似乎我需要为每个记录插入使用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一切都按预期工作。

我试图以“正确的方式”做到这一点:

替代文字http://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系统……