1.

What are different entity states in EF?

Answer»

There are five possible states where an entity can exist:

  • Added: It is a state in which an entity exists WITHIN the context but does not exist within the database. When the user invokes the SaveChanges method, DbContext usually generates an INSERT SQL QUERY to insert the data into the database. Upon successful COMPLETION of the SaveChanges method, the entity's state changes to unchanged.
  • Deleted: This state indicates that the entity is marked for deletion has not been removed from the database. Also, it indicates the existence of the entity in the database. When the user invokes the SaveChanges method, DbContext usually generates a DELETE SQL query to delete or remove the entity from the database. Upon successful completion of the delete operation, DbContext removes the entity.
  • Modified: When the entity is modified, its state BECOMES Modified. Also, it indicates the existence of the entity in the database. When the user invokes the SaveChanges method, DbContext usually generates an UPDATE SQL query to update the entity from the database. Upon successful completion of the SaveChanges method, the entity's state changes to unchanged.
  • Unchanged: Since the context retrieved the entity's property values from the database, the values have not changed. This entity is ignored by SaveChanges.
  • Detached: This state indicates that the entity is not TRACKED by the DbContext. If an entity was created or retrieved outside the domain of the current instance of DbContext, then its entity state will be Detached.

The following diagram represents the different entity states in Entity Framework:



Discussion

No Comment Found