Volume 3 · Chapter 2 — Entity Framework Core and Data Access Engineering
DbContext Lifecycle and Tracking
2.1 Introduction
TheDbContextis the heart of EF Core - a session between the application and the database that manages querying, change tracking, and transactions. Getting its lifetime right is critical, because misuse causes memory growth, stale data, connection problems, and threading errors. The two ideas that resolve most DbContext issues are: it should be short-lived (scoped to one request/unit of work), and tracking should be enabled only when you intend to save changes.
2.2 DbContext Is a Unit of Work
ADbContextnaturally implements the Unit of Work pattern: you load entities, modify them as plain objects, and a singleSaveChangescommits all the tracked changes together in one transaction. This is why one DbContext should represent one logical unit of work - typically one HTTP request.
sequenceDiagram autonumber participant App as Application participant Ctx as DbContext participant Track as Change Tracker participant DB as Database App->>Ctx: load entities (query) App->>App: modify objects Ctx->>Track: detect changes App->>Ctx: SaveChanges() Ctx->>DB: INSERT/UPDATE/DELETE in one transaction DB-->>Ctx: committed
2.3 Lifetime: Scoped Is Correct
In ASP.NET Core,AddDbContextregisters the context asscopedby default, so one instance serves one request and is disposed when the request ends. Transient would create too many contexts and lose the unit-of-work grouping; singleton is dangerous becauseDbContextis not thread-safe and its change tracker would accumulate state across all requests (a captive-dependency trap).
| Lifetime | Result |
|---|---|
| Scoped (default) | Correct - one context per request/unit of work |
| Transient | Too many contexts; loses unit-of-work grouping |
| Singleton | Unsafe - not thread-safe; shared/stale tracked state |
2.4 Entity States and Identity Resolution
EF Core tracks each entity’s state (Detached, Added, Unchanged, Modified, Deleted) to know what SQL to generate. Within a tracking context it also performs identity resolution - the same database row loaded multiple times returns the same object instance, keeping the object graph consistent.
2.5 Tracking vs No-Tracking
Tracking queries let EF Core detect and persist changes, but for read-only work that machinery is wasted overhead.AsNoTrackingskips it, reducing memory and speeding up materialization - the right default for reports, list screens, and API responses that never save the entities.
// Read-only: skip tracking for lower memory and faster reads.
var report = await context.Customers
.AsNoTracking()
.Where(c => c.IsActive)
.ToListAsync(ct);
// Read-modify-save: tracking ON (default) so SaveChanges detects the change.
var customer = await context.Customers.FirstAsync(c => c.Id == id, ct);
customer.Email = newEmail; // change tracker records this
await context.SaveChangesAsync(ct); // -> UPDATE
When should you use AsNoTracking, and why?
I useAsNoTrackingfor read-only queries - any query whose results I’m going to read but never modify and save back, such as list/search screens, reports, dashboards, and API responses that return data. The reason is that EF Core’s change tracking, which is on by default, does real work that’s pure overhead when you’re not going to save: for every entity it materializes, it creates and stores a snapshot of the original values so it can later detect changes, it maintains the entity in its identity map, and it does change detection - all of which cost memory and CPU proportional to the number and size of entities returned. For a read-only query returning thousands of rows, that tracking overhead is significant and buys nothing, because you never callSaveChangeson those entities.AsNoTrackingtells EF Core to materialize the results without tracking them, which lowers memory consumption and speeds up materialization, giving noticeably better performance for read-heavy paths. The trade-off is that no-tracking entities aren’t tracked, so you can’t modify them and callSaveChangesto persist - but that’s exactly fine for read-only scenarios, and it’s a feature not a limitation there. So the rule is simple: use tracking (the default) only for the read-modify-save pattern where you load an entity, change it, and save it; useAsNoTrackingfor everything you’re only reading. In practice a large fraction of an app’s queries are reads, so applyingAsNoTrackingto them (or setting a no-tracking default and opting into tracking where needed) is one of the easiest, highest-value EF Core performance improvements.
Why is a singleton DbContext dangerous, and what lifetime should it have?
ADbContextshould be scoped - one instance per request/unit of work, which is whatAddDbContextregisters by default in ASP.NET Core - and a singleton is dangerous for two fundamental reasons. First,DbContextis not thread-safe: it’s designed to be used by a single thread at a time, but a singleton would be shared across all concurrent requests and threads, so simultaneous operations on the same context corrupt its internal state and throw errors (EF even detects and throws on concurrent use). Second, the change tracker accumulates state: aDbContexttracks every entity it loads for its whole lifetime, so a long-lived (singleton) context would keep growing its tracked-entity set indefinitely - a memory leak - and would serve stale data because entities loaded once stay cached in the context and aren’t refreshed, and one request’s tracked changes would be visible to others. Making it scoped solves both: each request gets a fresh context, used by that request’s single logical flow, and disposed at the end, so tracked state is bounded to one request, there’s no cross-request data leakage or staleness, and there’s no concurrent access. Transient is also wrong because it would create many separate contexts within a single request, breaking the unit-of-work grouping (changes across repositories wouldn’t share one context/transaction) and adding overhead. So the correct lifetime is scoped, and the specific dangers of singleton are thread-safety violations under concurrency and unbounded, stale, cross-request tracked state - which is also a classic captive-dependency bug if a singleton service accidentally holds a scoped DbContext.
A reporting API's memory grows over time because it loads thousands of tracked entities it only displays. How do you fix it and prevent recurrence?
The immediate cause is that a read-only reporting path is loading large numbers of full entities with change tracking enabled, so EF Core is snapshotting and tracking thousands of entities per request that are never modified or saved - wasted memory and CPU that accumulates and pressures the heap. The direct fixes address both over-tracking and over-fetching. First, useAsNoTrackingon all these read-only queries so EF Core stops maintaining snapshots and identity maps for data that’s only displayed, which sharply reduces memory and speeds up materialization. Second, use projection: instead of loading whole entities (with all their columns and navigation properties) when the report only needs a handful of fields, project withSelectinto a lightweight DTO/anonymous type containing just the required columns, which transfers far less data from the database and allocates far less in memory. Third, paginate: never return unbounded result sets - page the data (ideally keyset pagination for very large tables) so each request handles a bounded amount. Together these turn a heavy, tracked, full-entity, unbounded query into a light, untracked, projected, paginated one. For heavy reporting specifically, I’d also consider a read-optimized model or reading from a replica rather than the transactional context. To prevent recurrence, I’d make these patterns the default and enforceable: set the DbContext (or query-level) tracking behavior to no-tracking for read paths so tracking is opt-in, establish a team convention that read/reporting queries project to DTOs and paginate, review generated SQL and query shapes in code review, add memory and query-performance monitoring so regressions surface early, and provide shared query helpers or a read model that bake in the right patterns. The root lesson is that read-heavy paths must be untracked, projected, and paginated - loading tracked full entities for display is a common, avoidable cause of memory growth - and making the efficient pattern the default is what stops it coming back.
2.6 Production Scenario
A reporting API’s memory climbs steadily. Investigation shows it loads thousands of fully-tracked entities per request even though it only displays read-only data. The team switches those queries toAsNoTracking, projects to lightweight DTOs selecting only needed columns, and adds pagination - and makes no-tracking the default for read paths - so memory plateaus and read performance improves.
Chapter Revision Notes
- DbContext is a short-lived Unit of Work - one per request/unit of work.
- Register it scoped (the default); singleton is unsafe (not thread-safe, stale/shared tracked state).
- Tracking enables change detection but costs memory/CPU - use AsNoTracking for reads.
- Identity resolution keeps the object graph consistent within a tracking context.
- Read paths should be untracked, projected, and paginated.