
Querying Again Won't Refresh Your Entity: How EF Core Change Tracking Works
- كاتب موثّق
- EF Core 10
محتويات المقال
Confirmed, and anyone can see it in the database. The SQL log shows the job's SELECT going out every three seconds, twenty times in a row. The job still times out, because every one of those queries handed back a payment whose Status was Pending.
The common misconception
DbContext is a database read. Run it again and you get whatever the row holds now, just like running the same SELECT twice in a SQL client.
AsNoTracking() is usually presented as a performance switch, so tracking looks like a speed detail rather than something that changes what your query returns.
What actually happens
The query runs, and the values are discarded
SaveChanges can work out what you changed. When a later tracking query returns a row, EF Core checks its key first. If an instance with that key is already tracked, EF Core returns that instance and doesn't overwrite its current or original values with the row it just read. This is : a context holds at most one instance per key.
Pending, a second context saved it as Confirmed, and the first context queried it again. The SELECT appeared in the log, the result was the same object as before, and its Status was still Pending. Find(42) went one step further: for the tracked key, it returned the instance without sending any SQL.
The database picks the rows, the tracker picks the values
WHERE clause still runs on the server, so the set of rows is current. Their values aren't. In the same test, Where(p => p.Status == PaymentStatus.Confirmed) returned payment 42, an object whose Status still said Pending. With Include, a post that another context added showed up in the collection, a post it deleted stayed there, and a post it renamed kept its old title. A payment deleted in the database vanished from query results but stayed in the change tracker as Unchanged. Your own ExecuteUpdate on the same context has the same blind spot: it changes rows, not the objects you're holding.
Why EF Core works this way
SaveChanges a graph with no ambiguity. The price is that a context's picture of an entity is frozen at the moment it started tracking it. That's why Microsoft designs DbContext for a short-lived : create it, load, change, save, dispose.
Where it bites: contexts that live too long
BackgroundService that resolves it once before its loop, a singleton holding one (the captive dependency problem), a Blazor Server component, where the scope lasts as long as the user's circuit, a desktop app, or a test that seeds and asserts through the same context.
The fix: a new context for each unit of work
using Microsoft.EntityFrameworkCore;public sealed class PaymentWatcher(ShopDb db){ public async Task<bool> WaitAsync(int id, CancellationToken ct) { for (var attempt = 0; attempt < 20; attempt++) { // The SELECT runs, but returns the instance tracked on attempt 0 var payment = await db.Payments.SingleAsync(p => p.Id == id, ct); if (payment.Status == PaymentStatus.Confirmed) return true; await Task.Delay(TimeSpan.FromSeconds(3), ct); } return false; // tested: never saw Confirmed }}using Microsoft.EntityFrameworkCore;public sealed class PaymentWatcher(IDbContextFactory<ShopDb> factory){ public async Task<bool> WaitAsync(int id, CancellationToken ct) { for (var attempt = 0; attempt < 20; attempt++) { // A new, empty context per check builds the entity from the row await using var db = await factory.CreateDbContextAsync(ct); var payment = await db.Payments.SingleAsync(p => p.Id == id, ct); if (payment.Status == PaymentStatus.Confirmed) return true; await Task.Delay(TimeSpan.FromSeconds(3), ct); } return false; }}IDbContextFactory<ShopDb>, registered with AddDbContextFactory, and creates a context for each check. Each one starts with nothing tracked, so the query builds the entity from the row it reads. In the test, the first check after the webhook returned Confirmed. Contexts from a factory aren't owned by the DI container, so await using disposes them.
AsNoTracking() | ||
Select) | ||
Entry(e).ReloadAsync() | ||
Entry(e).GetDatabaseValuesAsync() | ||
ChangeTracker.Clear() |
How to apply it in your project
Find contexts that outlive one operation Look for a DbContextin singletons, in static fields, in Blazor components, and inBackgroundServicecode that resolves it before a loop.Give each operation its own context Register AddDbContextFactoryand callCreateDbContextAsyncper iteration or message, or create a scope withIServiceScopeFactoryper iteration and resolve the context from it.Don't track what you only read Use AsNoTracking()or project to a DTO for queries that display or check data. A read-heavy context can default toQueryTrackingBehavior.NoTracking, withAsTracking()for the few queries that save.Refresh on purpose, and protect your writes Call ReloadAsync()before changing an entity you've held for a while, and put concurrency tokens on rows that more than one process edits.
Key takeaways
A tracking query always runs its SQL, but for keys the context already tracks it returns the existing instance and ignores the row's values. The database decides which rows come back; the change tracker decides what values you see. Finddoesn't even query for a tracked key.The behavior protects unsaved changes and keeps one instance per key, which is why a DbContextshould live for a single unit of work.Get fresh values with a new context, AsNoTracking(), a projection,ReloadAsync()orChangeTracker.Clear().Stale tracked values can overwrite newer data on save; a concurrency token turns that into an exception.
التعليقات (0)