O'Reilly logo

Programming Entity Framework: DbContext by Rowan Miller, Julia Lerman

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Using Snapshot Change Tracking

Snapshot change tracking depends on Entity Framework being able to detect when changes occur. The default behavior of the DbContext API is to automatically perform this detection as the result of many events on the DbContext. DetectChanges not only updates the context’s state management information so that changes can be persisted to the database, it also performs relationship fix-up when you have a combination of reference navigation properties, collection navigation properties and foreign keys. It’s important to have a clear understanding of how and when changes are detected, what to expect from it and how to control it. This section addresses those concerns.

Understanding When Automatic Change Detection Occurs

The DetectChanges method of ObjectContext has been available since Entity Framework 4 as part of the snapshot change tracking pattern on POCO objects. What’s different about DbContext.ChangeTracker.DetectChanges (which in turn, calls ObjectContext.DetectChanges) is that there are many more events that trigger an automatic call to DetectChanges. Here is the list of the method calls you should already be familiar with that will cause DetectChanges to do its job:

  • DbSet.Add

  • DbSet.Find

  • DbSet.Remove

  • DbSet.Local

  • DbContext.SaveChanges

  • Running any LINQ query against a DbSet

There are more methods that will trigger DetectChanges. You’ll learn more about these methods throughout the rest of this book:

  • DbSet.Attach

  • DbContext.GetValidationErrors

  • DbContext.Entry

  • DbChangeTracker.Entries ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required