【问题标题】:Model updates to contained collection not saved in DB when saving parent entity?保存父实体时对包含集合的模型更新未保存在数据库中?
【发布时间】: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


    【解决方案1】:

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

    类似:p.CaseRefs.ForEach(c =&gt; db.Entry(c).State = EntityState.Modified);

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-11-05
      • 1970-01-01
      • 2019-11-17
      • 1970-01-01
      相关资源
      最近更新 更多