EF Core performance: fixing N+1 queries and lazy loading by aggregating in the database

EF Core Interview Q&A November 13, 2026 csharp

N+1 queries: one query per order.

csharp
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
// ======================================================================
// Q: This is slow with 10,000 orders. Why?
//
// - N+1 queries: one query per order.
// - The whole table is loaded into memory.
// Fix: do the calculation in the database.
// Other tools: AsNoTracking() for reads, projection with Select instead of
// Include, AsSplitQuery() when many Includes cause a cartesian explosion. To see
// the SQL: LogTo or Application Insights.
// ======================================================================

// Slow version (lazy loading)
var orders = await _db.Orders.ToListAsync();
foreach (var o in orders)
    total += o.Lines.Sum(l => l.Quantity * l.UnitPrice); // lazy loading

// Fix: compute the sum in the database
var total = await _db.OrderLines
    .Where(l => l.Order.CreatedAt >= from)
    .SumAsync(l => l.Quantity * l.UnitPrice, ct);