skip to content

In EF Core 10, when does ChangeTracker.DetectChanges run automatically, and what goes wrong if AutoDetectChangesEnabled is set to false?

level: seniorimportance: should knowfreq 38%

answer

  1. snapshot compared with current values
  2. SaveChanges, Entries, HasChanges, Local
  3. Entry() detects one entity only
  4. AutoDetectChangesEnabled defaults to true
  5. ChangeTracker.Clear() for long-lived contexts

basics

~20 s

DetectChanges compares every tracked entity with its snapshot. SaveChanges, Entries, HasChanges, CascadeChanges and DbSet.Local run it automatically; Entry runs it for one entity. With AutoDetectChangesEnabled false, plain property edits go unsaved unless DetectChanges is called first.

solid answer

~40 s

With the default snapshot strategy, EF Core does not see a property assignment; `ChangeTracker.DetectChanges()` finds edits by comparing each tracked entity's current values with the snapshot taken when it was tracked, so its cost grows with the number of tracked entities and properties. It runs automatically in `SaveChanges`/`SaveChangesAsync`, `ChangeTracker.Entries()`/`Entries<T>()`, `HasChanges()`, `CascadeChanges()` and `DbSet<T>.Local`; `Entry(x)` and the entry's `Property`, `Collection`, `Reference` and `Member` methods detect changes for that one entity only. `AutoDetectChangesEnabled` (default `true`) turns the automatic calls off. Then `Add`, `Remove`, `Attach` and state assignments still register, but an edit to a property of a tracked entity is invisible: `SaveChanges` sends no `UPDATE` for it unless you call `DetectChanges()` yourself. Disable it only in a narrow `try`/`finally`.

code

csharp · 9 lines
csharp
db.ChangeTracker.AutoDetectChangesEnabled = false;

var customer = await db.Customers.SingleAsync(c => c.Id == id);
customer.Phone = "+44 20 7946 0000";

await db.SaveChangesAsync();          // no UPDATE: the edit was never detected

db.ChangeTracker.DetectChanges();     // compares with the snapshot
await db.SaveChangesAsync();          // UPDATE "Customers" SET "Phone" = ...

go deeper

for a junior

Remember that EF Core finds property edits by comparing with a snapshot, and that SaveChanges does that comparison for you.

for a middle

List the calls that run full detection and the ones that detect one entity, and explain why the cost grows with the number of tracked entities.

for a senior

Diagnose a slowing batch job or a silently lost edit from AutoDetectChangesEnabled, and prefer Clear, short-lived contexts or no-tracking reads over switching detection off.

for a principal

Decide whether a high-volume write path should keep snapshot tracking, move to notification entities, or bypass tracking, and how that choice is guarded in code review.

## Why EF Core needs DetectChanges With the default **snapshot change tracking**, entities are plain C# objects. Assigning `customer.Phone = "..."` runs an ordinary property setter; EF Core is not told. Instead, when an entity is tracked, EF Core stores a **snapshot** of its property values. `ChangeTracker.DetectChanges()` walks every tracked entity, compares current values with the snapshot, marks differing properties modified, moves their entities to `Modified`, and also picks up navigation and foreign-key changes so relationships are fixed up. The work is proportional to **tracked entities x properties**. The EF Core docs say it is not a bottleneck for most applications but can become one when a context tracks thousands of entities. ## Where it runs automatically Full detection over the whole graph: - `SaveChanges` and `SaveChangesAsync` - so every edit is found before commands are built; - `ChangeTracker.Entries()` and `Entries<TEntity>()` - so reported states are current; - `ChangeTracker.HasChanges()` - so its answer is accurate; - `ChangeTracker.CascadeChanges()` - so parent states are right before cascading; - `DbSet<TEntity>.Local` - so the local view is up to date. Local detection for **one entity**: - `DbContext.Entry(entity)` and the `EntityEntry` methods `Property`, `Collection`, `Reference` and `Member`; - `EntityEntry.DetectChanges()` when you call it explicitly; - when a dependent is about to be deleted because a required relationship was severed, to check whether it was re-parented. Local detection can miss changes that only a full scan would find - for example a cascade caused by an undetected change on another entity - so after bulk edits a full `ChangeTracker.DetectChanges()` is the safe call. ## What AutoDetectChangesEnabled = false changes `ChangeTracker.AutoDetectChangesEnabled` is `true` by default. Setting it to `false` removes every automatic scan listed above - the full ones and the per-entity ones that `Entry` runs. The consequences: 1. Calls that set state explicitly still work: `Add`, `Remove`, `Attach`, `Update`, `Entry(x).State = ...` and `Property(...).IsModified = true`. 2. Property edits on tracked snapshot entities are **not noticed**. A `SaveChanges` after `customer.Phone = "..."` sends no `UPDATE` for that change and reports success. 3. `HasChanges()`, `Entries()` and `Entry(x).State` may report stale states. 4. Calling `ChangeTracker.DetectChanges()` explicitly brings everything back in line. The pattern the docs show is to turn it off only around code that does not need detection - for example in a `SaveChanges` override that has just enumerated `Entries<T>()` (which already detected changes) and only set values on `Added` entities - inside `try`/`finally` so the flag is always restored: ```csharp public override int SaveChanges() { foreach (var entry in ChangeTracker.Entries<Customer>()) // detects changes { /* inspect states */ } try { ChangeTracker.AutoDetectChangesEnabled = false; return base.SaveChanges(); // skip a second scan } finally { ChangeTracker.AutoDetectChangesEnabled = true; } } ``` ## Keeping the tracked set small instead The better fix for slow detection is usually tracking fewer entities, not switching detection off: - create a new `DbContext` per unit of work, as a scoped context in a web request already does; - in a long batch loop, call `ChangeTracker.Clear()` after each saved batch. It stops tracking every entity at once, is far faster than detaching entities one by one, and does not raise `StateChanged` events; - read data that is never modified with a no-tracking query; - for very large tracked sets, consider notification entities, which report their own changes so no scan is needed. ## Observing it `ChangeTracker` raises `DetectingAllChanges`/`DetectedAllChanges` around a full scan and `DetectingEntityChanges`/`DetectedEntityChanges` around a per-entity one, which is a cheap way to confirm in a test how often scans happen. `ChangeTracker.DebugView.LongView` shows the result: before detection an edited property is still shown as unmodified; after it, the property is marked `Modified` with its original value.

  • A nightly job imports 200,000 CRM contacts through one DbContext and slows down as it runs. What do you change?
    Each `SaveChanges` scans everything still tracked, so later batches pay for earlier ones. Save in batches and call `ChangeTracker.Clear()` after each one, or create a new context per batch. Clear drops all entries at once without per-entity `StateChanged` events. Turning off `AutoDetectChangesEnabled` is safe only if nothing in the loop edits entities that are already tracked.
  • Why can db.Entry(customer).State show Modified while ChangeTracker.HasChanges() would be the safer check before a save?
    With default settings `Entry` runs local detection for that one entity, so its own state is current. `HasChanges()` runs a full scan, so it also reflects edits on every other tracked entity and cascades caused by them, which local detection can miss.

  • DetectChanges runs only when SaveChanges is called.
  • With AutoDetectChangesEnabled off, SaveChanges still notices edited property values.
  • DetectChanges re-reads rows from the database to compare them.
  • ChangeTracker.Clear() raises StateChanged for every entity it stops tracking.
  • Detaching entities one by one is the fast way to empty a context.