Model updates to contained collection not saved in

2019-05-14 06:25发布

问题:

Issue: Child model collection in MVC3 & Entity Framework 4.1 is being updated properly in model via Edit action but the values are not being saved in DB.

Overview: - Model object Person contains object CaseRef's - Person property updates are getting saved in the DB on db.SaveChanges() but internal collection CaseRef property updates are not being saved - All values are bound/mapped correctly upon entry of HttpPost ActionResult Edit() so the model is being updated successfully from Form submit (Edit View).

Models:

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 - Edit (Post)

    [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");
        }

回答1:

Setting db.Entry(p).State = EntityState.Modified; you only set the parent entity to modified. To also modify the navigational properties you have to mark them all as modified.

So something like: p.CaseRefs.ForEach(c => db.Entry(c).State = EntityState.Modified);