Version 4.1 of the Entity Framework contains both the Code First approach and the new DbContext API. This API provides a more productive surface for working with the Entity Framework and can be used with the Code First, Database First, and Model First approaches. This is the last post of a twelve part series containing collections of patterns and code fragments showing how features of the new API can be used.
Automatically detecting changes
When using most POCO entities the determination of how an entity has changed (and therefore which updates need to be sent to the database) is made 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. By default, the Entity Framework does this detection automatically when the following methods are called:
Disabling automatic detection of changes
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. For example:
using (var context = new UnicornsContext())
context.Configuration.AutoDetectChangesEnabled = false;
// Make many calls in a loop
foreach (var unicorn in myUnicorns)
context.Configuration.AutoDetectChangesEnabled = true;
Don’t forget to re-enable detection of changes after the loop—I used a try/finally to ensure it is always re-enabled even if code in the loop throws an exception.
An alternative to disabling and re-enabling is to leave automatic detection of changes turned off at all times and either call context.ChangeTracker.DetectChanges explicitly or use change tracking proxies diligently. Both of these options are advanced and can easily introduce subtle bugs into your application so use them with care.
In this part of the series we looked when DbContext automatically detects changes in your tracked entities and gave some guidance as to when this automatic change detection should be turned off.
As always we would love to hear any feedback you have by commenting on this blog post.
ADO.NET Entity Framework