Change Tracking in Entity Framework

Change Tracking in Entity Framework

In this article, I am going to discuss Change Tracking in Entity Framework Database First Approach with Examples. Please read our previous article where we discussed DbEntityEntry Class in Entity Framework Database First Approach. We are going to work with the same example that we created in our Introduction to Entity Framework Database First Approach article. Please read our Introduction to Entity Framework Database First Approach article before proceeding to this article.

Change Tracking in Entity Framework

Let us understand, how Entity Framework tracks changes in entities during their lifetime. The Entity Framework supports automatic change tracking of the attached entities during the lifetime of the context. The DbChangeTracker class in Entity Framework gives you all the information about current entities which are being tracked by the context object.

Please note that every entity must have a key (primary key) property in order to be tracked by the context object. If the Primary key property is not available, then that entity will not be tracked by the context object.

The following example shows how the Entity Framework context object tracks the entities and the changes that occurred on them.

using System;
using System.Data.Entity.Infrastructure;
using System.Linq;
namespace DBFirstApproach
{
    class Program
    {
        static void Main(string[] args)
        {
            using (EF_Demo_DBEntities context = new EF_Demo_DBEntities())
            {
                //Disabling Dynamic Procy
                context.Configuration.ProxyCreationEnabled = false;

                Console.WriteLine("Find Student Whose Student Id: 1");
                var student = context.Students.Find(1);

                Console.WriteLine($"Context Object Tracking Changes of {context.ChangeTracker.Entries().Count()} Entities");
                DisplayTrackedEntities(context.ChangeTracker);

                Console.WriteLine("Find Standard Whose Standard Id: 1");
                var standard = context.Standards.Find(1);
                
                Console.WriteLine($"Context Object Tracking Changes of {context.ChangeTracker.Entries().Count()} Entities");
                DisplayTrackedEntities(context.ChangeTracker);
                Console.WriteLine("");

                Console.WriteLine("Editing Standard Entity");
                student.FirstName = "FirstName Updated";
                DisplayTrackedEntities(context.ChangeTracker);

                Console.WriteLine("");
                Console.WriteLine("Editing Standard Entity");
                standard.StandardName = "Standard Name Updated";
                DisplayTrackedEntities(context.ChangeTracker);

                //Creating a New Teacher Emtity
                Console.WriteLine("Adding New Teacher into the Context");
                Teacher tchr = new Teacher() { FirstName = "Pranaya", LastName = "Rout" };
                context.Teachers.Add(tchr);

                Console.WriteLine($"Context Object Tracking Changes of {context.ChangeTracker.Entries().Count()} Entities");
                DisplayTrackedEntities(context.ChangeTracker);
                Console.WriteLine("");

                Console.WriteLine("Remove Student Entity From the Context");
                context.Students.Remove(student);
                Console.WriteLine($"Context Object Tracking Changes of {context.ChangeTracker.Entries().Count()} Entities");
                DisplayTrackedEntities(context.ChangeTracker);
            }

            Console.Read();
        }

        private static void DisplayTrackedEntities(DbChangeTracker changeTracker)
        {
            // Gets the DbEntityEntry objects for all the entities tracked by the context object.
            var entries = changeTracker.Entries();
            foreach (DbEntityEntry entry in entries)
            {
                Console.WriteLine($"\nEntity Name: {entry.Entity.GetType().FullName}");
                Console.WriteLine($"Entity State: {entry.State}");
            }
            Console.WriteLine("\n---------------------------------------");
        }
    }
}
Output:
Find Student Whose Student Id: 1
Context Object Tracking Changes of 1 Entities

Entity Name: DBFirstApproach.Student
Entity State: Unchanged

---------------------------------------
Find Standard Whose Standard Id: 1
Context Object Tracking Changes of 2 Entities

Entity Name: DBFirstApproach.Student
Entity State: Unchanged

Entity Name: DBFirstApproach.Standard
Entity State: Unchanged

---------------------------------------

Editing Standard Entity

Entity Name: DBFirstApproach.Student
Entity State: Modified

Entity Name: DBFirstApproach.Standard
Entity State: Unchanged

---------------------------------------

Editing Standard Entity

Entity Name: DBFirstApproach.Student
Entity State: Modified

Entity Name: DBFirstApproach.Standard
Entity State: Modified

---------------------------------------
Adding New Teacher into the Context
Context Object Tracking Changes of 3 Entities

Entity Name: DBFirstApproach.Teacher
Entity State: Added

Entity Name: DBFirstApproach.Student
Entity State: Modified

Entity Name: DBFirstApproach.Standard
Entity State: Modified

---------------------------------------

Remove Student Entity From the Context
Context Object Tracking Changes of 3 Entities

Entity Name: DBFirstApproach.Teacher
Entity State: Added

Entity Name: DBFirstApproach.Standard
Entity State: Modified

Entity Name: DBFirstApproach.Student
Entity State: Deleted

---------------------------------------

As you can see in the output, the context object in Entity Framework keeps track of entities whenever we retrieve the entity, add a new entity, modify an existing entity, or delete an existing entity.

In the next article, I am going to discuss Logging Database Commands in Entity Framework Database First Approach with Examples. Here, in this article, I try to explain Change Tracking in Entity Framework Database First Approach with Examples. I hope you enjoy this Change Tracking in Entity Framework Database First Approach article.

Leave a Reply

Your email address will not be published. Required fields are marked *