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

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:

public ActionResult Edit(FormCollection form)
    // Get movie to update
    var id = Int32.Parse(form["id"]);
    var movieToUpdate = _db.MovieSet.First(m => m.Id == id);

    // Deserialize (Include white list!)
    TryUpdateModel(movieToUpdate, new string[] { "Title", "Director" }, form.ToValueProvider());

    // If valid, save movie to database
    if (ModelState.IsValid)

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

public ActionResult Edit(Course course)
     if (ModelState.IsValid)
         db.Entry(course).State = EntityState.Modified;

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.

        public void Update(MyObject obj) {
            //Update all but not relationship (scalar properties are updated)
            var fromDatabase = Database.Customers.Where(p=>p.Id==customer.ID);

            //Update reference
            if (obj.OtherObject!= null) {
            fromDatabase.OtherObject = obj.OtherObject;

            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).

If you like my article, think to buy my annual book, professionally edited by a proofreader. directly from me or on Amazon. I also wrote a TypeScript book called Holistic TypeScript

2 thoughts on “Entity Framework 4.3 Update a complex object from Asp.Mvc controller

  1. Pingback: Patrick Desjardins' Blog » Entity Framework 4.3 : How to insert, update, delete master-detail entity

  2. After reading back what I wrote I figure out that this post can be confusing with the terminology. What I meant with “complex” is not a complex object with Entity Framework but complex in the meaning of having object containing other object. This type of class doesn’t only contain scalar property but property to other class. Sorry for the possible confusion.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.