Skip to content
Tutorials Center
My learning

Topics

Lesson 27 of 41 ยท Change Tracking and Saving

How Change Tracking Works

Learn how EF Core change tracking works: entity states, snapshot comparison, DetectChanges, identity resolution, Entry and DebugView, and AsNoTracking, with a runnable snapshot-tracker stand-in.

Here is the code that surprises every newcomer:

C#
var product = await db.Products.FirstAsync(p => p.Id == 1);
product.Price = 19.99m;
await db.SaveChangesAsync();      // an UPDATE is sent. Who told EF Core?

You never called Update. EF Core knew, because the DbContext was watching the entity from the moment it came out of the query. This watching is called change tracking, and it is the heart of EF Core's SaveChanges. This lesson explains how it works, so that surprises become predictable.

EF Core is not runnable on this site, so the code above is read-only. The runnable blocks are stand-ins that implement the same idea (snapshots) in plain C#.

Entity states

Every entity the context knows about is in exactly one state:

State Meaning What SaveChanges does
Detached Not tracked by this context Nothing
Unchanged Tracked, matches the database Nothing
Added Tracked, not in the database yet INSERT
Modified Tracked, some property values changed UPDATE (only changed columns)
Deleted Tracked, marked for removal DELETE
stateDiagram-v2
    [*] --> Detached
    Detached --> Added: Add
    Detached --> Unchanged: Attach / query result
    Unchanged --> Modified: property changed
    Unchanged --> Deleted: Remove
    Added --> Unchanged: SaveChanges
    Modified --> Unchanged: SaveChanges
    Deleted --> Detached: SaveChanges

A query result starts as Unchanged; SaveChanges moves everything back to Unchanged (or Detached for deletes).

You can read the state at any time:

C#
EntityState state = db.Entry(product).State;   // Unchanged, Modified, ...

How EF Core notices a change: snapshots

When a query returns an entity, EF Core stores a snapshot of its original property values. When you call SaveChanges (or anything else that needs to know), EF Core runs DetectChanges: it compares each tracked entity's current values with its snapshot. Properties that differ are marked modified, and only those columns appear in the UPDATE statement:

SQL
UPDATE Products SET Price = @p0 WHERE Id = @p1;    -- Name and Stock are not touched

If you assign the same value (product.Price = product.Price) nothing is sent, because the snapshot still matches.

You can inspect the comparison:

C#
var entry = db.Entry(product);
foreach (var prop in entry.Properties.Where(p => p.IsModified))
{
    Console.WriteLine($"{prop.Metadata.Name}: {prop.OriginalValue} -> {prop.CurrentValue}");
}

Entities can also use change-tracking proxies or implement INotifyPropertyChanged to be told about changes instead of being compared, which is cheaper with huge numbers of entities. Snapshot tracking is the default and the right choice almost always.

Here is a snapshot tracker written from scratch. It follows the same steps: remember the original values, compare on save, send only what changed:

C# Stand-in: a snapshot change tracker

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Identity resolution

A context holds at most one tracked instance per primary key. Query the same row twice and you get the same object back:

C#
var a = await db.Products.FirstAsync(p => p.Id == 1);
var b = await db.Products.FirstAsync(p => p.Id == 1);
Console.WriteLine(ReferenceEquals(a, b));   // True: one tracked instance

The second query still goes to the database (queries always do), but EF Core returns the instance it already tracks and does not overwrite its current property values with the fresh row. This is why a long-lived context can show stale data. Find and FindAsync are the exception: they check the tracker first and skip the database when the entity is already tracked.

This also explains a classic error: trying to Attach a second object with the same key into the same context throws, because the identity map already has one.

C# Stand-in: an identity map

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

No-tracking queries

Tracking costs memory (the snapshot) and time (DetectChanges). For read-only queries, skip it:

C#
var list = await db.Products.AsNoTracking().Where(p => p.Stock > 0).ToListAsync();

AsNoTracking queries are faster and lighter, but the returned objects are not tracked: editing them and calling SaveChanges does nothing, and the same row can appear as several different objects. There is also AsNoTrackingWithIdentityResolution() when a graph shares entities, and you can make no-tracking the default:

C#
options.UseQueryTrackingBehavior(QueryTrackingBehavior.NoTracking);

A common rule for web APIs: GET endpoints use AsNoTracking (or projection), POST/PUT/DELETE endpoints use tracking.

Looking inside: DebugView

When a save does something unexpected, print what the tracker thinks:

C#
db.ChangeTracker.DetectChanges();
Console.WriteLine(db.ChangeTracker.DebugView.ShortView);
// Product {Id: 1} Modified Id:1 Price:4.50 -> 5.25 ...

ChangeTracker.Entries() lists every tracked entity, and db.ChangeTracker.Clear() detaches everything, which is useful in long-running loops (batch imports) to stop memory from growing.

Common mistakes

  • Reusing one context for too long. The tracker grows, data goes stale, and DetectChanges slows down. A context is a short unit of work: one request, one operation.
  • Editing no-tracking results and expecting a save. Nothing will be saved.
  • Expecting a second query to refresh values. It returns the already-tracked instance; reload with db.Entry(x).ReloadAsync() if you need fresh values.
  • Tracking a million rows to export them. Use AsNoTracking or stream the results.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. How does EF Core know which properties changed?

    DetectChanges compares each tracked entity's current values with its original-value snapshot.
  2. 2. What does AsNoTracking do?

    No-tracking queries skip snapshots and the identity map, so they are faster but their results are not saved.
  3. 3. You query the same row twice with a tracking query. What do you get?

    A context tracks at most one instance per key and returns it again.
  4. 4. Which state does a freshly queried entity have?

    Query results are tracked as Unchanged until a property is modified.
  5. 5. Which statement about the UPDATE EF Core sends is true?

    Only the changed columns appear in the SET clause, and nothing is sent until SaveChanges.

Summary

  • The context tracks entities in states: Detached, Unchanged, Added, Modified, Deleted.
  • Snapshots plus DetectChanges let EF Core build UPDATE statements with only changed columns.
  • One tracked instance per key (identity resolution); repeat queries do not refresh tracked values.
  • Use AsNoTracking for read-only queries; keep contexts short-lived; inspect with Entry and DebugView.

Next: SaveChanges and transactions