Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does DetectChanges work?

There is the following 2 entities, with the following properties:

Parent
    ID
    Children
Child
    ID
    ParentID
    Parent

Now I have the following code:

db.Configuration.AutoDetectChangesEnabled = false;

var child1=new Child();
parent.Children.Add(child1);
db.ChangeTracker.DetectChanges();
parent.Children.Remove(child1);

var child2=new Child();
child2.Parent=parent;
child2.ParentID=parent.ID;
db.Children.add(child2);

At this point, child1 and child2 are completely identical. The Parent and ParentID properties have the same values (that of parent). Examining the dbContext entry for both of them also shows exactly the same information, e.g. OriginalValues is empty for both.

If I now call db.ChangeTracker.DetectChanges however, child1.Parent becomes null, while child2.Parent keeps its value. How does EF know to do this - where does it keep the info needed to be able to make this difference?

Thank you for any ideas

like image 400
wezten Avatar asked Oct 20 '14 08:10

wezten


1 Answers

In general

Detect Changes works by detecting the differences between the current property values of the entity and the original property values that are stored in a snapshot when the entity was queried or attached.

Entity Framework Automatic Detect Changes

and

Ensures that ObjectStateEntry changes are synchronized with changes in all objects that are tracked by the ObjectStateManager.

ObjectContext.DetectChanges Method

so in your example after you disable change tracking the new values are on top of the original values until you decide to update the model by calling context.ChangeTracker.DetectChanges and synchronize all objects (it more or less defers the operations). Now when you call DetectChanges all operations (Remove & Add) get commited to the model so that they can be saved later. Thus the parent is removed from the child1 parent.Children.Remove(child1) and child2 keeps its value because here the operation was to add the parent (assignment).

The reason why you would want to disable change tracking is performace:

If you are tracking a lot of entities in your context and you call one of these methods many times in a loop, then you may get significant performance improvements by turning off detection of changes for the duration of the loop.

If you'd like to know the exact technical/implementation details you can digg through the source code:

.NET Framework source code online > DetectChanges

like image 85
t3chb0t Avatar answered Sep 28 '22 05:09

t3chb0t