保存父实体时,对包含的集合的模型更新未保存在DB中?

gen*_*eek 3 entity-framework-4.1 asp.net-mvc-3

问题: MVC3和实体框架4.1中的子模型集合正在通过编辑操作在模型中正确更新,但这些值未保存在DB中.

概述: - 模型对象Person包含对象CaseRef - 人员属性更新将保存在db.SaveChanges()上的DB中,但内部集合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; }  
}
Run Code Online (Sandbox Code Playgroud)

控制器 - 编辑(发布)

    [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");
        }
Run Code Online (Sandbox Code Playgroud)

Wou*_*ort 6

设置db.Entry(p).State = EntityState.Modified;您只将父实体设置为已修改.要修改导航属性,您必须将它们全部标记为已修改.

所以类似于: p.CaseRefs.ForEach(c => db.Entry(c).State = EntityState.Modified);