Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change Tracking Discrepancy with DbContext and EF Code First

When it comes to using EF Code First there are two options for change tracking:

  1. Snapshot based Change Tracking
  2. Notification based Change Tracking with Proxies

Consider the following code when run using each method of change tracking. Assume a DbContext instance with the default configuration options. 

var o = context.MySet.First();
o.MyProperty = 42;
context.SaveChanges();

If the entity instance loaded and tracked by the context on the first line already has a value of 42 for "MyProperty" then its state in the change tracker is different during the call to "SaveChanges" on the third line. 

  1. Snapshot based Change Tracking - its state is "Unchanged". 
  2. Notification based Change Tracking with Proxies - its state is "Modified". 

Given that under notification based change tracking an unnecessary update statement will be sent to the database during the call to "SaveChanges" I envisage most developers would prefer the behaviour of snapshot based change tracking. 

Is this difference in behaviour intentional?

Is there a way to achieve the same behaviour as snapshot based change tracking when using notification based change tracking with proxies?

Note that I believe this is related to this feature suggestion - http://data.uservoice.com/forums/72025-entity-framework-feature-suggestions/suggestions/1015363-better-change-tracking-for-poco-proxies

like image 439
Matt Brooks Avatar asked Jun 18 '12 21:06

Matt Brooks


1 Answers

This behavior is intentional. The reason is backward behavioral compatibility with old EntityObject based entities which behaved in the same way - they count changing property to the same value as a real modification. The linked article also shows that the new recommendation is to use snapshot change tracking and select change tracking proxies only if you have performance problem with snapshot change tracking.

like image 62
Ladislav Mrnka Avatar answered Oct 06 '22 15:10

Ladislav Mrnka