Sub topic 12
How Change Tracking Works
In the last chapters you changed a C# object, called SaveChangesAsync, and the database was updated. You never had to tell EF Core which objects had changed. This chapter explains how EF Core knows.
What Change Tracking Is
Change tracking is EF Core's way of watching the entities that a DbContext loads or adds. The part of the context that does this watching is called the change tracker. For each entity, the change tracker stores two things:
- A snapshot, which is a copy of the entity's values as they were when EF Core first saw it.
- A state, which is a label that tells EF Core what to do with the entity on the next save.
When you call SaveChangesAsync, EF Core compares every tracked entity with its snapshot. This step is called detecting changes. EF Core then writes SQL for each entity based on its state.
The Entity States
| State | Meaning | SQL on save |
|---|---|---|
| Detached | The context does not track the entity | None |
| Added | A new entity that is not in the database yet | `INSERT` |
| Unchanged | Loaded or saved, and not changed since then | None |
| Modified | One or more properties differ from the snapshot | `UPDATE` |
| Deleted | Marked for removal | `DELETE` |
Watching the States Change
You can ask the context for an entity's state with db.Entry(entity).State. This program uses the BloggingContext from earlier chapters and 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
blog.Url = "https://example.com/changed";
db.ChangeTracker.DetectChanges();
Console.WriteLine(db.Entry(blog).State); // Modified
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); // DetachedSetting blog.Url does not change the state right away. The state changes when EF Core detects changes. SaveChangesAsync and Entry both detect changes for you. The program calls DetectChanges directly only to make that step visible.
No-Tracking Queries
Tracking costs memory and time, because EF Core has to keep a snapshot for every entity. If you only want to show data and never change it, add AsNoTracking to the query.
using Microsoft.EntityFrameworkCore;
using var db = new BloggingContext();
var blogs = await db.Blogs.AsNoTracking().ToListAsync();
Console.WriteLine(db.ChangeTracker.Entries().Count()); // 0
foreach (var b in blogs)
{
b.Url = "changed";
}
await db.SaveChangesAsync(); // Sends no SQL: nothing is trackedExercise
You load a Post with a normal query, set its Title to the value it already has, and call SaveChangesAsync. What state does the Post have, and does EF Core send an UPDATE?
Show answer
The Post stays Unchanged. EF Core compares the current value with the snapshot, finds no difference, and sends no UPDATE.
Exercise
A page only lists blog URLs and never edits them. Which query method should you add, and why?
Show answer
Add AsNoTracking. The page never saves changes, so EF Core does not need snapshots, and skipping them saves memory and time.