Navigation Property not being updated on db.SaveChanges()
我有一个从编辑视图中获取
工具模型包含一个名为
在controller方法中,我通过使用
我的代码:
工具控制器。编辑(工具工具):
1 2 3 4 5 6 7 8 9 10 | int id = db.MobileUsers.Single(x => x.Name == tool.HolderName).Id; tool.Holder = db.MobileUsers.Find(id); if (ModelState.IsValid) { db.Entry(tool).State = EntityState.Modified; db.SaveChanges(); return RedirectToAction("Index"); } return View(tool); |
工具类中的holder导航属性:
1 | public virtual MobileUser Holder { get; set; } |
我最终放弃了,转而使用了graphdiff。工作得很好,如果将来有人遇到这个问题,我建议你这样做。
首先,不要在控制器的语音中使用实体模型(使用viewmodels),然后显示模型。IAC,试试这个:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 | [HttpPost] public ActionResult Edit(Tool tool): if (ModelState.IsValid) { // If you want to update fields in tool.Holder, do something like this: var newHolder = tool.Holder; // save changes from view. // Fetch the current Holder from database tool.Holder = db.MobileUsers.Single(x => x.Name == tool.HolderName); // Replace the changed properties. Many ways to do this. I like Automapper. tool.Holder.Field1 = newHolder.Field1; tool.Holder.Field2 = newHolder.Field2; // etc. db.Entry(tool).State = EntityState.Modified; // Below not needed since you getched it into the context // db.Entry(tool.Holder).State = EntityState.Modified; // Need to set child state as well db.SaveChanges(); return RedirectToAction("Index"); } return View(tool); } |
在ViewModel场景中,您的文章将获取工具和持有者,映射中的更改并保存,而不公开整个实体。