LINQ Interview Question #109

How can LINQ cause the N+1 query problem?

LINQ Performance, EF Core LINQ, Expressions & Advanced Queries Senior Advanced

Quick Interview Answer

N+1 occurs when one query loads a set of parent records and additional queries are then executed separately for related data for each parent. This can happen with certain lazy-loading or per-item query patterns.

Detailed Explanation

N+1 occurs when one query loads a set of parent records and additional queries are then executed separately for related data for each parent. This can happen with certain lazy-loading or per-item query patterns.

The result can be a large number of database round trips. Appropriate projection, eager loading, explicit loading strategies, or query restructuring can prevent it.

Code Example

// Prefer a projection that retrieves required related data
// as part of an intentional query shape.
var orders = await db.Orders
    .Select(o => new
    {
        o.Id,
        CustomerName = o.Customer.Name
    })
    .ToListAsync();