LINQ Interview Question #111

When should Select be preferred over Include?

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

Quick Interview Answer

Select is often preferable when the application needs a specific read model rather than a tracked entity graph. Projection can retrieve exactly the fields required and can calculate or reshape data directly in the query.

Detailed Explanation

Select is often preferable when the application needs a specific read model rather than a tracked entity graph. Projection can retrieve exactly the fields required and can calculate or reshape data directly in the query.

Include is appropriate when full related entities are required as part of an entity graph, particularly when those entities will be used as entities rather than merely displayed.

Code Example

var orders = await db.Orders
    .Select(o => new OrderDto
    {
        Id = o.Id,
        CustomerName = o.Customer.Name,
        LineCount = o.Lines.Count()
    })
    .ToListAsync();