Using ObjectStateEntry class, we can monitor the entities whether they are Entity Framework generated objects or POCO objects.
When are ObjectStateEntry objects created?
We know that whenever we query in Entity Framework, the results are entity objects and are attached to the ObjectContext. For every attached entity in the ObjectContext, ObjectStateManager creates an ObjectStateEntry object. This object contains data and state of the entity. This means that through ObjectStateEntry objects, we can only manage attached objects residing in the context. Whenever we detach an entity from the Objectcontext, the ObjectStateEntry object will be deleted automatically.
How to access ObjectStateEntry object?
Each and every ObjectContext maintains its own ObjectStateManager and can be accessed by the ObjectStateManager property of ObjectContext using the statement given below.
After this statement, we can access ObjectStateEntry objects using the following two methods.
GetObjectStateEntries() method returns a collection of ObjectStateEntry objects from the context.
GetObjectStateEntry() method returns a single ObjectStateEntry object from the context.
The basic difference between these methods in usage is explained below.
The GetObjectStateEntry() method takes an entity as an input and usage of this method is shown below.
The GetObjectStateEntries() method takes the EntityState enums as a parameter and returns entites which are in the entity state which you have asked for. The possible EntityState enums are :
The below code demonstrates how to use GetObjectStateEntries() method to get all the ObjectStateEntry objects of customer entity which are modified. After this we can access the data of each entity´s current values and original values of each and every property.
The ObjectStateEntry class exposes properties to read and write the data and methods to change the state of an entity. Sometimes, it is necessary to change the state of an entity before calling SaveChanges method.
ObjectStateEntry class properties and methods are given below.