How to change the state of an entity using ChangeObjectState method of ObjectStateManager

The ChangeObjectState method of ObjectStateManager is a very flexible method as compared to AcceptAllchanges method. Why I call it flexible is because unlike AcceptAllchanges method, which changes the state of all entities which are in Added or Modified state to Unchanged state, the ChangeObjectState method changes the state of an entity to any state.

This method takes two arguments, one is entity and other is the new state of an entity.
To understand where this method is exactly useful, suppose in a disconnected environment like tier based applications, we have written two methods, one method to retrieve customer data and display in the web form with one ObjectContext and another method the Update method to update customer data. In the Update method, we again create a new instance of ObjectContext and attach this entity to the ObjectContext and to persist the changes to the database, we call SaveChanges method. To your surprise, the changes are not persisted.

This happens whether you are updating EntityObjects or POCO objects. To complete our understanding of usefulness of ChangeObjectState method, we need to answer the question:

Why should we change the state of an entity before calling SaveChanges() method in a disconnected scenario?
The Attach() method attaches an object to the context in an Unchanged state. When we call SaveChanges method, the entities which are in Added, Modified and Deleted states only will be persisted to the database. So, after attaching an object, to trigger persistence action, we need to modify the state of the entity using ChangeObjectState() method. This method returns the ObjectStateEntry of an object as demonstrated with below code.

code for ChangeObjectState() method in disconnected scenario

As we can be seen from the output, after the changes are persisted to the database, the object state again goes to Unchanged state. The one issue we should be aware of whenever the state is modified using ChangeObjectState() method is that, this method marks all properties (scalar) as modified and UPDATE statement is constructed using all the properties. Another point to be noted is that this method affects both current and original values of ObjectStateEntry object.

We can also change the state of an entity from one to another using ChangeState() method of ObjectStateEntry class.