Entity States in Entity Framework

The Entity States represents the state of an entity. The Entity state can be Added, Deleted, Modified, Unchanged or Detached. DbContext tracks & manages the entity state of every entity using the ChangeTracker. For example, when we add a new entity to Context using the Add method, the DbContext sets the state of the entity as Added. When you call the SaveChanges method, the context sends an Insert Query to the database. Similarly, it uses it to create Insert,Update or Delete SQL queries, when we invoke the SaveChanges

Source Code:
The source code of this project available in GitHub.

Entity States

An entity is always in any one of the following states.

  1. Added
  2. Deleted
  3. Modified
  4. Unchanged
  5. Detached

Added

Added entity state indicates that the entity exists in the context, but does not exist in the database. The DbContext generates the INSERT SQL query and insert the data into the database when the user invokes the SaveChanges method. Once the SaveChanges is successful, the state of the entity changes to Unchanged

Unchanged

The property values of the entity have not been modified since context retrieved it the database. SaveChanges ignores this entity.


Best Entity Framework Books
The Best Entity Freamework Books, which helps you to get started with Entity Framework  

Modified

The entity state becomes Modified, when the user makes changes to the entity. It also indicates that the entity exists in the database. The DbContext generates the update SQL Query to update the entity in the database. Once the SaveChanges is successful, the state of the entity changes to Unchanged

In Connected Scenario, the Entity framework also keeps track of the changes made to the properties of the entity. The context updates only those columns whose values are modified.

Deleted

The Deleted entity state indicates that the entity is marked for deletion, but not yet deleted from the database. It also indicates that the entity exists in the database. The DbContext generates the delete SQL Query to remove the entity from the database. The DbContext removes the entity once the delete operation succeeds after the SaveChanges

Detached

The Detached entity state indicates that the DbContext is not tracking the entity.

References

Leave a Comment

Your email address will not be published.

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

Scroll to Top