Sub topic 12
How Change Tracking Works
In earlier chapters you changed a property on an object, called SaveChangesAsync, and the database was updated. You never told EF Core which property had changed. EF Core worked that out with a feature called change tracking. This chapter explains how that works, so the results stop being a surprise.
This chapter uses the Blog, Post, and BloggingContext classes from earlier chapters. Keep them in their own file in the EfCoreDemo project, and put the code samples in Program.cs.
What the Change Tracker Is
The change tracker is the part of a DbContext that remembers every entity it has loaded or been given. An entity is an object of a class that EF Core maps to a table, like Blog.
For each tracked entity, the change tracker stores two things:
- A state is a label that says what should happen to the entity at the next save, such as "insert it" or "update it".
- A snapshot is a copy of the property values taken when the entity was loaded from the database. EF Core compares the current values to this copy to find what changed.
When you call SaveChangesAsync, EF Core looks at every tracked entity, checks its state, and writes the matching SQL.
The Five Entity States
Each entity is in exactly one of these states.
| State | Meaning | SQL sent by SaveChanges |
|---|---|---|
| Detached | The context is not tracking the entity | Nothing |
| Added | New entity, not yet in the database | INSERT |
| Unchanged | Loaded from the database and not changed | Nothing |
| Modified | Loaded, then one or more properties changed | UPDATE |
| Deleted | Marked for removal | DELETE |
The diagram shows how an entity moves between states.
Watching States Change
You can read an entity's state with db.Entry(entity).State. This program prints the state after each step.
using Microsoft.EntityFrameworkCore;
using var db = new BloggingContext();
var blog = new Blog { Url = "https://example.com/tracking" };
Console.WriteLine(db.Entry(blog).State); // Detached
db.Blogs.Add(blog);
Console.WriteLine(db.Entry(blog).State); // Added
await db.SaveChangesAsync();
Console.WriteLine(db.Entry(blog).State); // Unchanged
Console.WriteLine(blog.BlogId); // The new key from the database
blog.Url = "https://example.com/changed";
Console.WriteLine(db.Entry(blog).State); // Modified
var urlProperty = db.Entry(blog).Property(b => b.Url);
Console.WriteLine(urlProperty.OriginalValue); // https://example.com/tracking
Console.WriteLine(urlProperty.CurrentValue); // https://example.com/changed
Console.WriteLine(urlProperty.IsModified); // True
await db.SaveChangesAsync();
Console.WriteLine(db.Entry(blog).State); // Unchanged
db.Blogs.Remove(blog);
Console.WriteLine(db.Entry(blog).State); // Deleted
await db.SaveChangesAsync();
Console.WriteLine(db.Entry(blog).State); // DetachedRun it with dotnet run. A few things to notice:
- After the first save, EF Core fills in
BlogIdwith the key the database generated. OriginalValuecomes from the snapshot.CurrentValueis what the object holds now.- The UPDATE sets only the
Urlcolumn, because onlyUrlis marked as modified.
How EF Core Notices a Change
A plain C# property has no way to tell EF Core that you changed it. So EF Core runs a step called DetectChanges, which compares every tracked entity with its snapshot.
EF Core runs DetectChanges for you at these moments:
- At the start of
SaveChangesandSaveChangesAsync. - When you call
db.Entry(entity)(for that one entity). - When you call
db.ChangeTracker.Entries().
This is why db.Entry(blog).State reported Modified right after the property changed.
Looking Inside the Change Tracker
To see everything the context is tracking, use ChangeTracker.Entries() or the debug view.
using Microsoft.EntityFrameworkCore;
using var db = new BloggingContext();
db.Blogs.Add(new Blog { Url = "https://example.com/one" });
db.Blogs.Add(new Blog { Url = "https://example.com/two" });
foreach (var entry in db.ChangeTracker.Entries())
{
Console.WriteLine($"{entry.Entity.GetType().Name}: {entry.State}");
}
Console.WriteLine(db.ChangeTracker.DebugView.LongView);DebugView.LongView prints every tracked entity with its state and property values. It helps when a save does something you did not expect. This program never saves, so nothing reaches the database.
Identity Resolution: One Row, One Object
A tracking context keeps only one object for each row. If two queries return the same row, you get the same object both times. This is called identity resolution.
using Microsoft.EntityFrameworkCore;
using var db = new BloggingContext();
db.Blogs.Add(new Blog { Url = "https://example.com/identity" });
await db.SaveChangesAsync();
db.ChangeTracker.Clear(); // Stop tracking everything
var first = await db.Blogs.FirstAsync(b => b.Url.EndsWith("identity"));
var second = await db.Blogs.FirstAsync(b => b.Url.EndsWith("identity"));
Console.WriteLine(ReferenceEquals(first, second)); // True
var third = await db.Blogs.AsNoTracking().FirstAsync(b => b.Url.EndsWith("identity"));
var fourth = await db.Blogs.AsNoTracking().FirstAsync(b => b.Url.EndsWith("identity"));
Console.WriteLine(ReferenceEquals(third, fourth)); // FalseIdentity resolution means you never have two copies of one row disagreeing inside the same context. ChangeTracker.Clear() makes the context forget all tracked entities without touching the database.
No-Tracking Queries
AsNoTracking() tells EF Core not to put query results into the change tracker. EF Core takes no snapshots and runs no comparisons, so the query is faster and uses less memory. The catch is that changes to those objects are not saved.
using Microsoft.EntityFrameworkCore;
using var db = new BloggingContext();
var blogs = await db.Blogs.AsNoTracking().ToListAsync();
foreach (var b in blogs)
{
b.Url = "https://changed.example.com";
}
int rows = await db.SaveChangesAsync();
Console.WriteLine(rows); // 0
Console.WriteLine(db.ChangeTracker.Entries().Count()); // 0SaveChangesAsync returns the number of rows written. Here it returns 0, because the context never knew about these objects.
Saving Changes to an Untracked Object
Sometimes you have an object the context is not tracking. It might come from a no-tracking query or from a web request. Update starts tracking it in the Modified state.
using Microsoft.EntityFrameworkCore;
using var db = new BloggingContext();
var blog = await db.Blogs.AsNoTracking().FirstAsync();
blog.Url = "https://example.com/updated-offline";
db.Blogs.Update(blog); // Detached -> Modified
Console.WriteLine(db.Entry(blog).State); // Modified
await db.SaveChangesAsync();Without a snapshot, EF Core cannot know which property changed. So Update marks every property as modified, and the UPDATE writes every column. Attach is the gentler option. It starts tracking the object as Unchanged, and only properties you change after attaching are saved.
Common Mistakes
- Changing no-tracking results and expecting a save. Nothing happens. Use a tracking query, or call
UpdateorAttach. - Keeping one context alive for a long time. The change tracker keeps growing, saves get slower, and the data goes stale. Create a context for one unit of work, then dispose it.
- Reading stale data. A tracked entity is not refreshed when a later query returns the same row. EF Core keeps your object as it is. Use
db.Entry(entity).ReloadAsync()or a new context to get fresh values.
Exercise
You load a Blog with a normal query, change its Url, then call Remove on it before saving. What state is the entity in, and what SQL does SaveChangesAsync send?
Show answer
The entity is in the Deleted state. Remove moves it from Modified to Deleted, so SaveChangesAsync sends a single DELETE for that row. The Url change is discarded and no UPDATE is sent. After the save, the entity is Detached.
Exercise
A page shows 5,000 products and never edits them. A teammate's query is db.Products.ToListAsync(). What one change would you suggest, and why?
Show answer
Add AsNoTracking(), as in db.Products.AsNoTracking().ToListAsync(). EF Core then skips 5,000 snapshots and tracker entries, which saves memory and time. The data is never saved, so tracking adds nothing.
Exercise
You call db.Blogs.Update(blog) on an object whose Url you changed. How many columns does the UPDATE write, and how would Attach behave differently?
Show answer
Update marks every property as Modified, so the UPDATE writes every non-key column (Url here). With Attach, the object starts as Unchanged. A Url change made before attaching is not saved. Only properties you change after Attach are detected and written.