Updating EntityFramework 4 Child list using MVC3
I'm trying to update a child collection (MVC3 and Entity Framework 4) I cant get any updates to get persisted.
[HttpPost]
public ActionResult Edit(Subject EditedSubject, IEnumerable<SubjectTagPin> SubjectTagPins)
{
开发者_开发技巧 try
{
XDataModelContainer model = new XDataModelContainer();
model.Subjects.Attach(EditedSubject);
model.SaveChanges();
return RedirectToAction("Index");
}
catch
{
return View(EditedSubject);
}
}
This is detached scenario. If you want to save changes in entities and in relations you must say EF what changes were executed. EF doesn't know it and it doesn't perform any automatic synchronization with the state in the database. This problemetic is known also as working with detached object graphs and in my opinion it is the biggest complexity in entity framework (and probably ORM globally). I answered similar question and you can also found related question here.
General answer is you must know which relations were created or removed and you must manually set either state of related object (in case of one-to-one or one-to-many) or state of relation (in case many-to-many). The complexity is even worse if you have many-to-many and you can create relation to existing objects, create new related objects or delete existing related objects in the same request.
My general advice is using less elegant but much easier approach: load your entity graph from the database and merge incomming changes into attached graph.
精彩评论