LINQ Interview Question #125

What are the main LINQ performance best practices for database queries?

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

Quick Interview Answer

Keep filters and projections on IQueryable until the intended execution boundary, select only required data, paginate large result sets, and use AsNoTracking for appropriate read-only entity queries. Avoid accidental multiple execution and premature materialization.

Detailed Explanation

Keep filters and projections on IQueryable until the intended execution boundary, select only required data, paginate large result sets, and use AsNoTracking for appropriate read-only entity queries. Avoid accidental multiple execution and premature materialization.

Also inspect generated SQL, prevent N+1 patterns, use suitable database indexes, prefer Any for existence checks, and move processing to the client only when it is intentional and the amount of data is controlled.

Code Example

var result = await db.Products
    .AsNoTracking()
    .Where(p => p.IsActive && p.Price >= minPrice)
    .OrderBy(p => p.Id)
    .Select(p => new ProductDto
    {
        Id = p.Id,
        Name = p.Name,
        Price = p.Price
    })
    .Take(100)
    .ToListAsync();