Working With Change Tracking Proxy in Entity Framework 6.0

In this article you will learn how to work with a Change Tracking Proxy in Entity Framework 6.0.

Introduction

Entity Framework is able 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. Change tracking happens through snapshot change tracking for the most POCO entity type. In the snapshot change tracking, a snapshot of the entity is taken when it loads or is attached by context and this snapshot of entity is used to track changes on an entity by comparing the current value with the original value.

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.

Automatic change tracking is enabled by default in Entity Framework. We can disable change tracking by setting the AutoDetectChangesEnabled property of DbContext to false. If this property is set to true then the Entity Framework maintains the state of entities.

  1. using (Entities Context = new Entities())  
  2. {  
  3.     Context.Configuration.AutoDetectChangesEnabled = true;  

Example

Suppose I have a table called “DepartmentMaster” and I am doing some operation like create, update and delete. Now I want to track all changes on this entity.

DepartmentMaster

the following is the initial test data of the Department Master table:

test Data

Code for Getting Changed entity using Change Tracker of Context

The DbContext.ChangeTracker.Entries() method returns all the entities tracked by the DbContext. These entities are in the form of DbEntityEntry. Using the DbEntityEntry.Entity Property, we can determine the tracked entity with its state. The DbEntityEntry instances always contain a non-null Entity and also Stub entities and Relationship entries are not a part of this DbEntityEntry instances, so we do not need to do further filtration for these.

The following code can help us determine the tracked entities. Here the AuditLog class is useful for storing the details of the tracked entities, like table name, column name, action type, original value and new value.

  1. public class AuditLog  
  2. {  
  3.     public string State { getset; }  
  4.     public string TableName { getset; }  
  5.     public string RecordID { getset; }  
  6.     public string ColumnName { getset; }  
  7.     public string NewValue { getset; }  
  8.     public string OriginalValue { getset; }  
  9. }  
  10.   
  11. public static List<AuditLog> GetAuditLogData(Entities Context)  
  12. {  
  13.     List<AuditLog> AuditLogs = new List<AuditLog>();  
  14.     var changeTrack = Context.ChangeTracker.Entries().Where(p => p.State == EntityState.Added || p.State == EntityState.Deleted || p.State == EntityState.Modified);  
  15.     foreach (var entry in changeTrack)  
  16.     {  
  17.         if (entry.Entity != null)  
  18.         {  
  19.             string entityName = string.Empty;  
  20.             string state = string.Empty;  
  21.             switch (entry.State)  
  22.             {  
  23.                 case EntityState.Modified:  
  24.                     entityName = ObjectContext.GetObjectType(entry.Entity.GetType()).Name;  
  25.                     state = entry.State.ToString();  
  26.                     foreach (string prop in entry.OriginalValues.PropertyNames)  
  27.                     {  
  28.                         object currentValue = entry.CurrentValues[prop];  
  29.                         object originalValue = entry.OriginalValues[prop];  
  30.                         if (!currentValue.Equals(originalValue))  
  31.                         {  
  32.                             AuditLogs.Add(new AuditLog  
  33.                             {  
  34.                                 TableName = entityName,  
  35.                                 State = state,  
  36.                                 ColumnName = prop,  
  37.                                 OriginalValue = Convert.ToString(originalValue),  
  38.                                 NewValue = Convert.ToString(currentValue),  
  39.                             });  
  40.                         }  
  41.                     }  
  42.                     break;  
  43.                 case EntityState.Added:  
  44.                     entityName = ObjectContext.GetObjectType(entry.Entity.GetType()).Name;  
  45.                     state = entry.State.ToString();  
  46.                     foreach (string prop in entry.CurrentValues.PropertyNames)  
  47.                     {  
  48.                         AuditLogs.Add(new AuditLog  
  49.                                         {  
  50.                                             TableName = entityName,  
  51.                                             State = state,  
  52.                                             ColumnName = prop,  
  53.                                             OriginalValue = string.Empty,  
  54.                                             NewValue = Convert.ToString(entry.CurrentValues[prop]),  
  55.                                         });  
  56.   
  57.                     }  
  58.                     break;  
  59.                 case EntityState.Deleted:  
  60.                     entityName = ObjectContext.GetObjectType(entry.Entity.GetType()).Name;  
  61.                     state = entry.State.ToString();  
  62.                     foreach (string prop in entry.OriginalValues.PropertyNames)  
  63.                     {  
  64.                         AuditLogs.Add(new AuditLog  
  65.                                         {  
  66.                                             TableName = entityName,  
  67.                                             State = state,  
  68.                                             ColumnName = prop,  
  69.                                             OriginalValue = Convert.ToString(entry.OriginalValues[prop]),  
  70.                                             NewValue = string.Empty,  
  71.                                         });  
  72.   
  73.                     }  
  74.                     break;  
  75.                 default:  
  76.                     break;  
  77.             }  
  78.         }  
  79.     }  
  80.     return AuditLogs;  

Test application code

In the test application, I have done create, update and delete operations on the DepartmentMaster entity and am trying to catch changes using the Change tracking proxy.

  1. static void Main(string[] args)  
  2. {  
  3.     List<AuditLog> auditLogs = new List<AuditLog>();  
  4.     using (Entities Context = new Entities())  
  5.     {  
  6.         // Add new Value  
  7.         DepartmentMaster dept = Context.DepartmentMasters.Create();  
  8.         dept.Name = "New Added Department";  
  9.         dept.Code = "AAA";  
  10.         Context.DepartmentMasters.Add(dept);  
  11.   
  12.         //Modify the existing Value  
  13.         DepartmentMaster deptUpdate = Context.DepartmentMasters.Find(1);  
  14.         deptUpdate.Code = "BBB";  
  15.   
  16.         //Delete the existing value  
  17.         DepartmentMaster deptDelete = Context.DepartmentMasters.Find(2);  
  18.         Context.Entry(deptDelete).State = EntityState.Deleted;  
  19.   
  20.         auditLogs = GetAuditLogData(Context);  
  21.   
  22.         Console.WriteLine("Table Name \t\t Column Name \t Action \t Old Value \t New Value");  
  23.         Console.WriteLine("--------------------------------------------------------------------------------");  
  24.         foreach (AuditLog a in auditLogs)  
  25.         {  
  26.             if (string.IsNullOrEmpty(a.OriginalValue))  
  27.             {  
  28.                 a.OriginalValue = "\t\t";  
  29.             }  
  30.             if (string.IsNullOrEmpty(a.NewValue))  
  31.             {  
  32.                 a.NewValue = "\t";  
  33.             }  
  34.             Console.WriteLine(a.TableName + " \t " + a.ColumnName + "\t " + a.State + " \t " +        a.OriginalValue + " \t " + a.NewValue);  
  35.         }  
  36.   
  37.         Context.SaveChanges();  
  38.     }  

Output

Output:

The following is a snapshot of the database after code execution:

Database snap

The following are some rules that must be followed by classes to enable Change-tracking:

  • The class must be public and not sealed.
  •  All properties must be public or protected with virtual getters and setters.
  • Collection type navigation must be a type ICollection<T>. They cannot be IList<T>, List<T>, HashSet<T> and so on.
The following are the advantages of change tracking proxies:
  • Changes are detected immediately for the tracked entities instead of when DetectChanges is called.
  • In some scenarios when may get performance gains
The following are the disadvantages of change tracking proxies:
  • The rules are so restrictive.
  •  Complex properties still require snapshot change-tracking.
  •  The Behavior of entities may be different when being tracked by the context because proxies cannot use the context object when the entity is not tracked.
  •  It must use the DbSet.Create method to create instances of the entity classes. If we create an entity instance using the "NEW" keyword then it will not be change-tracked.
Performance of change-tracking proxies

The Performance of change-tracking proxies may be both advantageous and disadvantageous. Performance depends on what we do with the entities.

Change-tracking proxies are more useful and provide good performance when many entities are being tracked and changes are made to some of them. In snapshot change tracking, the system needs to scan and compare all entities to detect changes. With change tracking proxies, every change is detected immediately without the scanning of entities.

Now consider just the reverse scenario. There are several changes being made on tracked entities. There is an extra cost of recording changes made on the entities in this case, so performance will be worse.

Now consider the scenario in which the same values are being assigned in the properties of entities. In the snapshot change tracking changes are detected at the time of the DetectChanges() method called but with a Change Tracking proxy, every change is detected immediately, so the performance of a Change Tracking proxy is again worth in this case.

Complex Type and Change Tracking proxies

The same as Lazy loading, Change Tracking is also not supported for complex types. The reason is the complex type may not be real entities and the complex type based property is itself considered for change tracking.