Entity Framework Track Changes - Microsoft Entity Framework

What is Entity Framework Track changes?

Entity Framework provide aptitude to track the changes made to entities and their relationships, so the correct update are made on the database when the SaveChanges process of context is called. This is a key characteristic of the Entity Framework.

  • The Change Tracking tracks changes while adding new record(s) to the entity collection, modifying or removing existing entities.
  • Then all the changes are kept by the DbContext level.
  • These track changes are lost if they are not saved before the DbContext object is destroyed.
  • DbChangeTracker class gives you all the information about current entities being tracked by the context.
  • To track any entity by the context, it must have the primary key property.

In Entity Framework, change tracking is enable by defaulting. You can also stop change tracking by setting the AutoDetectChangesEnabled property of DbContext to false. If this property is set to true then the Entity Framework continue the state of entities.

Let’s take a look at the following instance in which the students and their enrollments are retrieve from the database.

When the above instance is compiled and executed you will receive the following output.

You can see that all data is only recover from the database that’s why the status is unmoved for all the entities.

Let us now take a look at another easy model in which we will add one more enrollment and delete one student from the database. Following is the code in which new enrollment is added and one student is deleted.

When the above instance is compiled and executed, you will obtain the following output.

You can now observe that the status of enrollment entity is set to added, and the status of student entity is deleted, because new enrollment has been added and one student is removed from the database.
We recommend that you perform the above example in a step-by-step mode for better understanding.

All rights reserved © 2018 Wisdom IT Services India Pvt. Ltd DMCA.com Protection Status

Microsoft Entity Framework Topics