C# Interview Question #175

What is the N+1 query problem?

EF Core, Data Access & Performance Senior Advanced

Quick Interview Answer

The N+1 problem occurs when an application executes one query to retrieve a list and then performs an additional query for each item to retrieve related data.

Detailed Explanation

The N+1 problem occurs when an application executes one query to retrieve a list and then performs an additional query for each item to retrieve related data.

For example, loading 100 orders and then separately querying each order's customer can result in 101 database queries.

It can be prevented through appropriate eager loading, projection, batching, or query redesign. SQL logging and profiling are useful for detecting unexpected repeated queries.

Code Example

var orders = await _context.Orders
    .AsNoTracking()
    .Select(o => new OrderDto
    {
        Id = o.Id,
        CustomerName = o.Customer.Name
    })
    .ToListAsync();