表Contact
通过*→1
密钥与表Location
有Location 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模型时禁止直接使用外键。
更新:Contact
和Location
都与User
UserID
有关。这可能是问题的根源吗?
答案 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();
}