EF不会保存外国数据

时间:2015-04-08 12:57:07

标签: c# asp.net-mvc entity-framework foreign-keys

Contact通过*→1密钥与表LocationLocation ID的关系。 以下代码保存除Contact之外的所有Location数据。 我做错了什么? EF 6.0.0.0,MVC 5.2.3.0,但EF 4.4和MVC 4也会导致此错误。

using(MyEntities me = new MyEntities())
{
  Contact ct = me.Contact.SingleOrDefault(x=>x.User.UserID == WebSecurity.CurrentUserId);
  ct.Title = "sometitle"; //assignment and saving works
  ct.Location = me.Location.SingleOrDefault(x=>x.Location_ID == 19); //only assignment works
  me.SaveChanges();
}

由于某些错误,我在从数据库创建EDMX模型时禁止直接使用外键。


更新:ContactLocation都与User UserID有关。这可能是问题的根源吗?

1 个答案:

答案 0 :(得分:2)

您必须指定位置级别必须包含在最后要保存的上下文中。

所以只需在代码中添加.Include(" Location")

using(MyEntities me = new MyEntities())
{
    Contact ct = me.Contact.Include("Location").SingleOrDefault(x=>x.User.UserID == WebSecurity.CurrentUserId);
    ct.Titile = "sometitle"; //assignment and saving works
    ct.Location = me.Location.SingleOrDefault(x=>x.Location_ID == 19); //only assignment works
    me.SaveChanges();
}