EF Core Query Tracking — Complete Guide
In this tutorial, you'll learn about EF Core Query Tracking. We cover key concepts, practical examples, and best practices.
By default, EF Core tracks every entity it returns from a query. Tracked entities are cached in the change tracker and checked for changes on SaveChanges. This is essential for updates but wasteful for read-only queries — tracking adds memory and performance overhead.
Default Behavior
// Tracking query (default)
var orders = await db.Orders.ToListAsync();
// Each order is tracked — stored in change tracker, snapshot taken
Output: Every Order is tracked. Memory grows with result set size. Snapshot comparison runs on SaveChanges.
Read-Only Optimization
// No-tracking query
var orders = await db.Orders
.AsNoTracking()
.ToListAsync();
// No tracking — faster, less memory
AsNoTracking() skips the change tracker entirely. Entities are returned as-is, no snapshot, no tracking overhead. Use this for read-only queries.
For query-level tracking changes:
// Identity resolution without tracking
var orders = await db.Orders
.AsNoTrackingWithIdentityResolution()
.ToListAsync();
// Deduplicates entities without full tracking overhead
Prevention
- Use
AsNoTracking()for all read-only queries (GET endpoints, reports, list views). - Use default tracking for queries where you will update entities.
- Use
AsNoTrackingWithIdentityResolution()when you need deduplication without tracking. - Set the default globally:
optionsBuilder.UseQueryTrackingBehavior(QueryTrackingBehavior.NoTracking). - Override with
AsTracking()for specific queries that need updates. - Avoid loading large result sets with tracking — memory grows with entity count.
- Combine
AsNoTrackingwithAsSplitQueryfor optimal read performance.
Common Mistakes with core query tracking
- Forgetting that lazy evaluation defers computation until the value is forced, causing space leaks with unevaluated thunks
- Using
returnto exit a function early instead of wrapping a pure value in the monad - Mixing let bindings with <- bindings in do notation, producing type errors
These mistakes appear frequently in real-world EF code. DodaTech's contributors have identified these patterns through analysis of open-source projects and production systems.
Practice Exercise
Write a pure function that safely divides two integers using Maybe, then test it with edge cases like division by zero and negative numbers.
This exercise reinforces the concepts covered in this guide. Try implementing it before checking online solutions.
FAQ
Query tracking is optimized for read-heavy workloads at DodaTech. For more EF Core, visit DodaTech.
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro