الانتقال إلى المحتوى
.NETEF Core· 7 دقائق للقراءة

Querying Again Won't Refresh Your Entity: How EF Core Change Tracking Works

A tracking query always runs its SQL, but for an entity the context already tracks, EF Core hands back the instance it has and ignores the new row.

ReadIn

مقال كل يوم يفرق معاك

21 نوفمبر 2026
  • كاتب موثّق
  • EF Core 10
محتويات المقال

A checkout flow waits for a payment provider's webhook. A background job checks the payment every three seconds and gives up after a minute. The webhook arrives after two seconds and sets the row to 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

The belief: a LINQ query on a 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.

It's an easy thing to believe, because half of it is true. The query really does go to the database every time, and the log proves it. Most code never sees the other half: in ASP.NET Core a context lives for one request, so almost every query is the first one that context runs for that row. And AsNoTracking() is usually presented as a performance switch, so tracking looks like a speed detail rather than something that changes what your query returns.

The missing half: EF Core runs the query, then decides for each row whether to use it at all.

What actually happens

The query runs, and the values are discarded

By default, a query that returns entity types is a tracking query. Every entity it returns is recorded in the context's with a snapshot of its original values, so 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.

In a test with EF Core 10 and SQLite, one context loaded payment 42 as 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

The 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

It's deliberate. If a query overwrote tracked values, it would silently wipe out changes you've made but not saved, and two objects with the same key could disagree about their properties and relationships. One instance per key gives 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

A scoped context in a web request rarely shows the problem. It shows up when a context outlives one operation: a 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

C# PaymentWatcher.cs
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    }}

The watcher now gets an 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.

When you can't replace the context, pick the tool that matches what you need:

OptionWhat you getUse it when
A new contextNew instances built from the rowsEach unit of work: the default
AsNoTracking()A separate copy; the tracked instance is untouchedRead-only checks and display
A projection (Select)Just the values; nothing is trackedYou need a few columns
Entry(e).ReloadAsync()The tracked instance overwritten from the row; unsaved edits are lostYou'll keep changing this entity
Entry(e).GetDatabaseValuesAsync()The row's values, without touching the entityComparing or merging values
ChangeTracker.Clear()Everything detached; later queries build new instancesA long batch loop on one context

How to apply it in your project

  1. Find contexts that outlive one operationLook for a DbContext in singletons, in static fields, in Blazor components, and in BackgroundService code that resolves it before a loop.
  2. Give each operation its own contextRegister AddDbContextFactory and call CreateDbContextAsync per iteration or message, or create a scope with IServiceScopeFactory per iteration and resolve the context from it.
  3. Don't track what you only readUse AsNoTracking() or project to a DTO for queries that display or check data. A read-heavy context can default to QueryTrackingBehavior.NoTracking, with AsTracking() for the few queries that save.
  4. Refresh on purpose, and protect your writesCall 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. Find doesn't even query for a tracked key.
  • The behavior protects unsaved changes and keeps one instance per key, which is why a DbContext should live for a single unit of work.
  • Get fresh values with a new context, AsNoTracking(), a projection, ReloadAsync() or ChangeTracker.Clear().
  • Stale tracked values can overwrite newer data on save; a concurrency token turns that into an exception.

📚 المصادر

  1. Tracking vs. No-Tracking Queries — EF Core, Microsoft Learn
  2. Identity Resolution — EF Core, Microsoft Learn
  3. Change Tracking in EF Core — Microsoft Learn
  4. DbContext Lifetime, Configuration, and Initialization — EF Core, Microsoft Learn
  5. Handling Concurrency Conflicts — EF Core, Microsoft Learn

التعليقات (0)