Suppose you are working with a console application on the server and you have created an entity data model with applicant entity as shown below.
You want to instantiate an existing applicant entity, modify a specific property and send only the changed properties to the database.
There are two approaches to completing the above task. You can use STE entity as POCO object and leverage the ObjectContext’s api to mark individual properties as modified. Another option is to make use of the ChangeTracker available on each entity to track its own changes and when you are done you can replay those changes on the ObjectContext using ApplyChanges method.
Using STE as POCO on the server
Since STE is nothing but POCO objects with additional capabilities for change tracking, we can take advantage of snap shot or notification based change tracking to notify changes to our objects. Code below shows an example.
In the code above, I am attaching an existing applicant entity, modifying its Name and calling SaveChanges to save the applicant object. The above code uses snap shot based change tracking where just before saving the applicant object, EF calls DetectChanges which compares the original values of the object to the current values and tries to find out what has changed. Since the only change made is Name, it will only create an update statement with Name property as modified.
Leveraging Change Tracking on the server
If you use Self Tracking Entity on the server, you do not have to worry about the object context, you can use the change tracker for each entity to keep track of its changes and when you are done you can spin up an object context and replay those changes using ApplyChanges method. Code below shows an example.
In the code above, I am marking applicant object as un changed because by default when you instantiate a STE, it is marked in Added state. By marking it as UnChanged, it starts the tracking on the object. In the next line where i modify the Name property, the entity gets into modified state. At this point i spin up an instance of ObjectContext and replay those changes using ApplyChanges method.
I forgot to mention another subtle change you have to make to the STE template. By default the template marks all properties as modified so you need to customize the template where it only marks properties that have changed. Make the following changes.
OriginalValueMembers originalValueMembers = new OriginalValueMembers(metadataLoaded, metadataWorkspace, ef);
Change the above line to the following
OriginalValueMembers originalValueMembers = new OriginalValueMembers(false, metadataWorkspace, ef);
Change the following in the context template
Change it to