【发布时间】:2011-12-14 05:26:58
【问题描述】:
问题: MVC3 和实体框架 4.1 中的子模型集合正在通过编辑操作在模型中正确更新,但值未保存在数据库中。
概述: - 模型对象 Person 包含对象 CaseRef 的 - Person 属性更新保存在 db.SaveChanges() 上的数据库中,但内部集合 CaseRef 属性更新未保存 - 输入 HttpPost ActionResult Edit() 后,所有值都已正确绑定/映射,因此模型已从表单提交(编辑视图)成功更新。
型号:
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; }
}
控制器 - 编辑(发布)
[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");
}
【问题讨论】:
标签: asp.net-mvc-3 entity-framework-4.1