Lesson 5 of 9 · 29m
EF Core Query Performance: Read the SQL Before Production Does
Control tracking, projection, includes, pagination, and query shape so Entity Framework Core remains a productivity tool rather than a latency amplifier.
Entity Framework Core does not usually fail because it is slow. It fails because nobody looked at the SQL it generated until production showed them. LINQ is expressive enough to hide enormous work: client evaluation, cartesian explosion, unbounded includes, and queries that fetch rows only to count or discard them. Senior EF work begins with the query log, not the entity diagram.
Tracking is a cost center
DbContext tracks entities so it can detect changes and write them later. For read-only endpoints, that tracking is pure overhead:
var orders = await db.Orders
.AsNoTracking()
.Where(o => o.CustomerId == customerId)
.OrderByDescending(o => o.CreatedAt)
.Take(50)
.ToListAsync(ct);Use tracking when you intend to mutate and save entities in the same unit of work. Do not use it because it is the default. In high-read APIs, the default should usually be the opposite.
Project before the database gives you too much
Returning entity graphs directly from a public API is both an over-fetching problem and a contract leak. Project the shape you need:
var rows = await db.Orders
.AsNoTracking()
.Where(o => o.CustomerId == customerId)
.Select(o => new OrderSummaryDto(
o.Id,
o.Number,
o.Status,
o.Lines.Sum(line => line.Quantity * line.UnitPrice)))
.ToListAsync(ct);Projection reduces bytes on the wire, avoids lazy-loading surprises, and makes authorization-visible fields explicit. It also exposes whether a calculated value is translated into SQL or evaluated in memory.
Includes can multiply rows
A graph like order -> lines -> product -> inventory snapshots can explode row count because every parent row repeats for every child row. EF Core can split queries when appropriate:
var orders = await db.Orders
.AsSplitQuery()
.Include(o => o.Lines)
.Where(o => o.Status == OrderStatus.Open)
.ToListAsync(ct);Split queries are not automatically better; they trade one large join for multiple round trips. Measure. Sometimes the correct answer is not an include at all but a purpose-built query per use case.
Keyset pagination beats offset for hot feeds
Offset pagination scans and discards rows as pages deepen:
ORDER BY created_at DESC
OFFSET 20000 ROWS FETCH NEXT 50 ROWS ONLY;At depth, this is latency waiting for a traffic spike. Keyset pagination uses the last observed value:
var page = await db.Orders
.AsNoTracking()
.Where(o => o.CreatedAt < cursor)
.OrderByDescending(o => o.CreatedAt)
.Take(51)
.ToListAsync(ct);Use a tie-breaker such as ID when timestamps are not unique. Cursor APIs are harder for random access but far better for operational feeds and infinite-scroll interfaces.
Log and benchmark realistic data shapes
Enable sensitive logging only in controlled development. Better, capture command logging and compare execution plans in the database:
options.LogTo(Console.WriteLine, LogLevel.Information);Look for repeated queries inside loops, missing indexes, non-sargable predicates, and unexpected row counts. EF.Functions providers can expose database-specific operations, but abstraction leaks are sometimes the correct trade when the alternative is a query that cannot use an index.
Field notes
- A compiled model and compiled queries help hot paths, but they do not rescue a bad query shape.
IQueryablepassed across layers makes the database contract invisible; materialize deliberately at a boundary.- Batch endpoints need explicit query planning. N sequential queries inside a loop are the ORM version of a rate-limit incident.
- SQL logging in production must be sampled or structured carefully; statement text can contain sensitive data.
Was this lesson helpful?