Entity Framework Core Interview Question #102
How does EF Core detect changes to tracked entities?
Change Tracking, Updates, Transactions & Concurrency Mid-Level Intermediate
Quick Interview Answer
EF Core commonly uses snapshot change detection. When an entity starts being tracked, EF Core records original values. During change detection it compares current values with those originals to determine which properties changed.
Detailed Explanation
EF Core commonly uses snapshot change detection. When an entity starts being tracked, EF Core records original values. During change detection it compares current values with those originals to determine which properties changed.
Change detection is automatically triggered by many DbContext operations, including SaveChanges. It can also be invoked explicitly through ChangeTracker.DetectChanges.
For normal applications, automatic detection is appropriate. Disabling it should only be considered for measured high-volume scenarios and must be handled carefully.
Code Example
var product = await db.Products.FindAsync(id);
product!.Price = 99m;
db.ChangeTracker.DetectChanges();
var entry = db.Entry(product);
Console.WriteLine(entry.State); // Modified