The Persisting of the Entities to the database is the responsibility of the DbContext object. It does so by keeping track of State of Entities. It keeps track of, whether entities in memory are in sync with their corresponding rows in the database. The DbContext uses this information to determine, what to do when the SaveChanges method is called.
For example, when you add a new entity to Context using the Add method, the DbContext sets the state of the Entity as Added. Then when you call the SaveChanges method, the context sends an Insert Query to the database
An entity is always in any one of the following states.
Added entity state indicates that the entity exists in the context, but does not exist in the database. DbContext generates the INSERT SQL query and insert the data into the database when the saveChanges method is invoked. Once the saveChanges are successful the state of the entity is changed to Unchanged
The property values of the entity have not been modified since it was retrieved from the database. SaveChanges ignores this entity.
The Modified entity state indicates that the entity is modified but not updated in the database. It also indicates that the entity exists in the database. The Dbcontext generates the update SQL Query to remove the entity from the database. Once the saveChanges is successful the state of the entity is changed to Unchanged
In Connected Scenario the Entity framework also keeps track of the properties that have been modified. The Columns in the Update statement is set for only those columns, who’s values are modified.
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 entity is removed from the context once the delete operation succeeds after the saveChanges
The Detached entity state indicates that the entity is not being tracked by the context.