We have seen why we should track changes in POCO entities and ways of change tracking mechanisms in a related article. There are two ways to track changes. One is Snapshot Change Tracking using DetectChanges method
and without using proxies and the other is Change Tracking with proxies. This article demonstrates another way of change-tracking mechanism by proxies.
As we know, whenever a scalar property is changed, the entity inherited from EntityObject notifies the ObjectContext about the change. This will enable ObjectContext to keep track of entity state. In the same way, to enable entities to notify their changes, we create change tracking proxies. To create these proxies, we should follow a few rules.
The SOM model used in this article contains Customer and SalesOrder entities having one-to-many relationship between them.
Every property should be declared with virtual keyword and we know it will not be a pure POCO class. When we declare the property as virtual, EF creates a dynamic proxy class at runtime. This proxy class gives not only the change notification functionality but also relationship fix up and Lazy loading capabilities to the class. Because of these created proxy classes, entities notify their changes automatically and continuously (the same way EntityObject class does).
Next, I will demonstrate How Change tracking proxies work, with an example. Firstly, we create classes as given in the code above.
1.The code retrieves the customer information whose CustomerID is 16 and changes the name of the customer.
2. At this point of time, if we display the ObjectStateEntry objects, you will see that they are current (the values in the entities and ObjectStateEntry objects are same). The synchronization happens automatically as proxies notify ObjectStateManager about changes in entities and we need not call DetectChanges() method to synchronize them. The comparision between original and current values will not happen and this is a more efficient mechanism. However, proxies create serialization problems, so they cannot be used in enterprise applications.