问题:MVC3 和 Entity Framework 4.1 中的子模型集合正在通过编辑操作在模型中正确更新,但值未保存在数据库中。
概述: - 模型对象 Person 包含对象 CaseRef's - Person 属性更新正在通过 db.SaveChanges() 保存在数据库中,但内部集合 CaseRef 属性更新未保存 - 所有值都在输入 HttpPost ActionResult Edit() 时正确绑定(bind)/映射,因此模型从表单提交(编辑 View )成功更新。
模型:
public class Person
{
public Person()
{
this.CaseRefs = new HashSet<CaseRef>();
}
// <...more properties here...>
public string Name { get; set; }
public int UserId {get; set}
public virtual ICollection<CaseRef> CaseRefs { get; set; }
}
public class CaseRef
{
// <...more properties here...>
public int DescId { get; set; }
public virtual Person Person { get; set; }
}
Controller - 编辑(发布)
[HttpPost]
public ActionResult Edit(Person p)
{
if (ModelState.IsValid)
{
// NOTE: At this point all fields from Edit form have been saved to the model
// specifically the internal CaseRefs Collection value updates.
db.Entry(p).State = EntityState.Modified;
// This is saving changes to Person.Name but not saving changes to the updated
// values in CaseRefs collection
db.SaveChanges();
return RedirectToAction("Index");
}
最佳答案
设置 db.Entry(p).State = EntityState.Modified;
您只需将父实体设置为已修改。要同时修改导航属性,您必须将它们全部标记为已修改。
所以类似于:p.CaseRefs.ForEach(c => db.Entry(c).State = EntityState.Modified);
关于asp.net-mvc-3 - 保存父实体时未保存在数据库中的包含集合的模型更新?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7877649/