我正在尝试使用EF 7保存对象但是当我尝试更新它时,我的外键值(导航属性)会丢失。运行下面的代码后,外键在数据库中都为空。
UserTask s = new UserTask()
{
Id = 10027,
Description ="test change",
Title = "Test change",
DueDate = DateTime.Now.AddHours(3),
CreatedBy = db.Users.Where(c=>c.UserName=="Bob").First(),
AssignedTo = db.Users.Where(c => c.UserName == "Stephen").First(),
Status = stat
};
db.UserTasks.Attach(s);
db.Entry(s).State = EntityState.Modified;
db.SaveChanges();
答案 0 :(得分:1)
您没有在变量" s"中设置FK,例如s.Fk1Id,因此该字段将为null。首先从EF获取实例:
var s = db.UserTasks.Where(o=>o.Id=="10027").First();
s.Id = 10027;
s.Description ="test change";
s.Title = "Test change";
s.DueDate = DateTime.Now.AddHours(3);
s.CreatedBy = db.Users.Where(c=>c.UserName=="Bob").First();
s.AssignedTo = db.Users.Where(c => c.UserName == "Stephen").First();