Entity Framework 4.3 Update a complex object from Asp.Mvc controller<!-- --> | <!-- -->Patrick Desjardins Blog
Patrick Desjardins Blog
Patrick Desjardins picture from a conference

Entity Framework 4.3 Update a complex object from Asp.Mvc controller

Posted on: March 27, 2012

Having to update an object from an edit action is pretty standard. In fact, it's also very straight forward with basic object (without containing other object). You could use the FormCollection way to do it:

1[AcceptVerbs(HttpVerbs.Post)] public ActionResult Edit(FormCollection form) {
2 // Get movie to update
3 var id = Int32.Parse(form["id"]);
4 var movieToUpdate =_db.MovieSet.First(m => m.Id == id);
6// Deserialize (Include white list!)
7TryUpdateModel(movieToUpdate, new string[] { "Title", "Director" }, form.ToValueProvider());
9// If valid, save movie to database
10if (ModelState.IsValid) {
11 _db.SaveChanges();
12 //...

Or, you could use the ability of auto binding each http parameters:

2public ActionResult Edit(Course course) {
3 if (ModelState.IsValid) {
4 b.Entry(course).State = EntityState.Modified; db.SaveChanges();
5 //...

However, the problem remain that these two examples are only good for object with scalar properties. This mean that it works fine until you have object that reference other object. In real life, you have a lot of change that you will handle complex object that contain reference to many to many others objects or to optional object or to 1 to 1 object.

To be able to handle those scenario, you need to handle scalar data and reference object separately. Here is an example of saving a complex object and its references.

1public void Update(MyObject obj) {
2 //Update all but not relationship (scalar properties are updated)
3 var fromDatabase = Database.Customers.Where(p=>p.Id==customer.ID);
4 Database.Entry(fromDatabase).CurrentValues.SetValues(obj);
6 //Update reference
7 if (obj.OtherObject!= null) {
8 Database.OtherObjects.Attach(obj.OtherObject);
9 }
10 fromDatabase.OtherObject = obj.OtherObject;
12 return Database.SaveChanges();

This check if the reference is null from the form. If yes, it mean that we need to save NULL to be able to have NULL in the foreign key of the database. If not, you need to attach to the Database Context the object (even if this one is not fully loaded, we just need the primary key to be available).