How it works: Track Changes using the Snapshot Tracking mechanism

Description Article
Table of Contents

The DbContext API automatically perform the detection of the changes occurred Through the DbContext.DetectChanges method.

This method triggers the process of detection of any changes occured in the entity objects tracked by the DbContext object. It can be called automatically or explicitly in the code.


How it works

When the DetectChanges method is called, it internally invokes the ObjectContext.DetectChanges method. The following list of methods calls automatically trigger the detect changes process:

  • DbSet.Find
  • DbSet.Remove
  • DbSet.Local
  • DbContext.SaveChanges
  • DbSet.Attach
  • DbContext.GetValidationErrors
  • DbContext.Entry


In most cases DetectChanges is fast enough that it doesn’t cause performance issues. However, when a very large number of objects exists in memory or a significantly number of operations are issued consecutively on DbContext, the behavior may be a performance concern.

When to disable automatic behavior

The following scnearios are elegible to switch off the default automatic behavior:

  • Performance issues;
  • A significantly number of operations are issued consecutively on DbContext without changing any object;
  • Data-binding scenarios where the UI change one of the navigation properties (or the foreign key property) and is required to have the other properties in the relationship to be updated to reflect the change.

When disbaled the developer will be responsible for calling the DetectChanges method before SaveChanges or somewhere else in the code whenever it is needed.

Disable the automatic detect changes mechanism
How to do it
using (var context = new BreakAwayContext())
    context.Configuration.AutoDetectChangesEnabled = false