Domdhi logoDOMDHI.OS
BACK_TO_COURSE

From SQL to Entity Framework

N+1: The Bug That Passes Every Test

One Query, Then a Hundred More

This is one of the most common EF performance bugs, and AI writes it all the time because the code reads so nicely:

// WRONG
var orders = await db.Orders
    .OrderBy(o => o.OrderId)
    .Take(100)
    .ToListAsync();               // 1 query

foreach (var order in orders)
{
    var lines = await db.OrderLines
        .Where(l => l.OrderId == order.OrderId)
        .ToListAsync();           // 1 query per order
}

One query for the list, then one more for every row: 101 trips to the database. That's N+1. With 5 test orders on your laptop it's instant. With thousands of orders and a database across the network, the page hangs.

Lazy loading hides it completely. If that's turned on (it's optional, through the proxies package), just touching a property runs a query:

foreach (var order in orders)
{
    Console.WriteLine(order.Customer.Name); // query
    Console.WriteLine(order.Lines.Count);   // another query
}

In a test database, that loop over 100 orders, each from a different customer, ran 201 queries. Nothing in that code looks like a database call.

Without lazy loading it can be worse: it's wrong. If nobody loaded them, order.Customer is null and the code crashes. That's the good outcome. order.Lines is usually an empty list, so order.Lines.Count says 0. No error. A total of zero on a real order.

The Fix: Ask Once for Exactly What You Need

// RIGHT: 1 query
var rows = await db.Orders
    .OrderBy(o => o.OrderId)
    .Take(100)
    .Select(o => new
    {
        o.OrderId,
        CustomerName = o.Customer.Name,
        LineCount = o.Lines.Count,
        Total = o.Lines.Sum(l => l.Quantity * l.UnitPrice)
    })
    .ToListAsync();

This is a projection: pick the values you want. Inside one query, o.Customer.Name becomes a join instead of a trip. This should be the default for screens and reports.

When you need the full objects, usually to change and save them, use Include. But include two lists at once and you get Module 1's fan-out: an order with 50 lines and 20 payments comes back as 50 × 20 = 1,000 rows instead of 71. EF puts the objects back together correctly, but all that data still crosses the wire. Split it:

var orders = await db.Orders
    .Where(o => o.CustomerId == 42)
    .Include(o => o.Lines)
    .Include(o => o.Payments)
    .AsSplitQuery()     // 3 queries, no multiplying
    .ToListAsync();

The count stays at three no matter how many orders. One caution: those are three separate queries, so data can change between them unless you wrap them in a suitable transaction.

How to Catch It

Turn on logging and count the queries:

options.UseSqlServer(connectionString)
       .LogTo(Console.WriteLine, LogLevel.Information);

Load 10 rows, then 100. If the number of queries grows with the rows, that's N+1. Then tell the AI:

Find every place in this code where a query runs inside a
loop, or a navigation property is read that wasn't loaded.
For each one, show the projection that replaces it, and
tell me the number of queries before and after.
INFO

An N+1 fails no unit test, because every answer is right. The only test that catches it is one that counts queries. Have the AI write that test for your important pages.

QUIZ

A page runs 11 queries for 10 orders and 101 queries for 100 orders. What is it?

Sign in to track lesson progress and earn a certificate.SIGN IN TO SAVE PROGRESS