LINQ Interview Question #108

Why should LINQ database queries project only required columns?

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

Quick Interview Answer

Selecting only the required fields reduces the amount of data read from the database, transferred over the network, materialized into objects, and held in memory.

Detailed Explanation

Selecting only the required fields reduces the amount of data read from the database, transferred over the network, materialized into objects, and held in memory.

For read-only pages and APIs, projecting directly into DTOs or view models is often more efficient than loading complete entities when most entity properties are not needed.

Code Example

var items = await db.Products
    .Where(p => p.IsActive)
    .Select(p => new ProductListDto
    {
        Id = p.Id,
        Name = p.Name,
        Price = p.Price
    })
    .ToListAsync();