1

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);
            }
        }
4
  • This will indeed saves nothing because Attach by default sets everything to Unchanged state. So what are you trying to achieve? Commented Mar 27, 2011 at 1:33
  • I did try to change the state from object state manager to modified, with no effect. Commented Mar 27, 2011 at 8:39
  • I'm trying to save a changed object + save child collection (mainly new items added) Commented Mar 27, 2011 at 8:41
  • Someone, please give sample code related to the question and @Ladislav Mrnka answer. Commented Apr 7, 2011 at 1:13

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

2 Comments

it would be nice if you add some code snippets to this answer to provide a full insight, especially for EF beginners :) thanks :)
Just describe exactly what you want to do. Including what navigation properties you want to modify and what type of relation do you have. Also describe if you just adding relation to existing objects or if you are also adding new objects.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.