Changing Entity’s State in Entity Framework 4.1

dbcontextentity-framework-4.1

Let say we have a Customer object which has an Order object. The Order object has OrderDetail object.

Customer oCustomer 
using(var context = new MyContext)
{
oCustomer = context.Include("Order.OrderDetail").Find(1);
}
oCustomer.Name ="blah blah";
oCustomer.Order.Description = "blah blah";
oCustomer.Order.OrderDetail.Quantity = 10;

Now when I change the state of Customer as following:

using(var context = new MyContext)
{
    context.Entry(oCustomer).State = EntityState.Modified.
    context.SaveChanges();
}

This saves only oCustomer object and not the Order and OrderDetail that are in oCustomer. Since context.Entry(oCustomer).State = EntityState.Modified changes state of oCustomer only and not the Order and OrderDetail. Currently, I have to change the state of each entity in the ObjectGraph manually so that the changes are saved. Is there any way to change the state of whole ObjectGraph instead of just the parent entity? Is there any extension method or any other way out to do that?

Best Answer

Since you are cutting the link between the context and the entity, no. It can not automagically know all the entries are in the modified state.

You could create your own extension method (or add it to your derived object context class) to walk over all the properties and check if they are mapped in the configuration and if so, set them to modified.

I assume you're working in a disconnected environment, the easiest way is to redo all the changes you've don in the other process. Load the entity from the db again, and populate the properties and call save changes.