保存父实体时,包含的集合的模型更新没有保存在数据库中?
问题: MVC3和Entity Framework 4.1中的子模型集合正在模型中通过“编辑”操作正确更新,但值不会保存在数据库中。
概述: -型号对象者包含对象CaseRef的-人物属性更新越来越保存在数据库上db.SaveChanges(),但内部集合CaseRef属性更新不被保存-所有值绑定/在HttpPost的ActionResult编辑的条目(正确映射),所以模型正在从表单提交(编辑视图)成功更新。
楷模:
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");
        }
  设置db.Entry(p).State = EntityState.Modified;  您只能设置要修改的父实体。  要修改导航属性,您必须将它们全部标记为已修改。 
  因此,类似于: p.CaseRefs.ForEach(c => db.Entry(c).State = EntityState.Modified); 
上一篇: Model updates to contained collection not saved in DB when saving parent entity?
下一篇: Updating references using entity framework in ASP.NET MVC 3
