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