ViAMAGAZINE | ViASTUDY The Stories That Matter. Click here
Follow Me On Google News Follow Now!

Entity States in Entity Framework

EF API maintains the state of each entity during an its lifetime. Each entity has a state based on the operation performed on it via the context class. The entity state represented by an enum System.Data.Entity.EntityState in EF 6 and Microsoft.EntityFrameworkCore.EntityState in EF Core with the following values:
  1. Added
  2. Modified
  3. Deleted
  4. Unchanged
  5. Detached
The Context not only holds the reference to all the entity objects as soon as retrieved from the database, but also keeps track of entity states and maintains modifications made to the properties of the entity. This feature is known as Change Tracking.
The change in entity state from the Unchanged to the Modified state is the only state that's automatically handled by the context. All other changes must be made explicitly using proper methods of DbContext or DbSet. (You will learn about these methods in EF 6 and EF Core sections.)
EF API builds and executes the INSERT, UPDATE, and DELETE commands based on the state of an entity when the context.SaveChanges() method is called. It executes the INSERT command for the entities with Added state, the UPDATE command for the entities with Modified state and the DELETE command for the entities in Deleted state. The context does not track entities in the Detached state. The following figure illustrates the significance of entity states:
Thus, entity states play an important role in Entity Framework.

Post a Comment