Entity framework tracking objects

Entity framework tracking objects

A tracking object exists when EF core will keep information about the entity in its change tracker. For an entity to be tracked, it must at least have a primary key.

By default, if you do a query to the database and it returns an entity, it will keep track of that entity by creating a tracking object. If the entity is already in the context (= A tracking object already exists), it will return the same instance.

On the official documentation, they refer to it as:

What are tracking objects?

Entity Framework provides ability to track the changes made to entities and their relations, so the correct updates are made on the database when the SaveChanges method of context is called. This is a key feature of the Entity Framework.

Difference between DbContext and ChangeTracker

A dbContext is a representation of a session within the database, the session of a dbcontext does not begin when the context is instantiated but only starts when you ask the context to do something (like querying a database).

A changeTracker will manage a collection of EntityEntry objects. An EntityEntry object is a tracking object of an existing entity in the context that keeps the state info of the object it is tracking.

What is an entity?

A running application has a number of objects in memory. If the DbContext has an EntityEntry change object about something it retrieved before, we call it an entity.

Tracking states

  • Unchanged (default)

  • Added

  • Modified

  • Deleted

What is done with these tracking objects?

So when an object is retrieved from the database, EF will create a tracking object for this entity and this tracking object will have the state of the entity it is tracking.

When you do changes to this entity, the entityEntry will have a tracking state of modified, meaning that the changes should be saved to the database.

If the SaveChanges() method is called, it will check the state tracking value and if it is not unchanged, it will create a new SQL statement that has all changes that are made to this object, executing the SQL in the DB and afterwards putting the state of the entityEntry object back to unchanged.