C# Interview Question #176

What is projection in EF Core, and why is it important?

EF Core, Data Access & Performance Senior Advanced

Quick Interview Answer

Projection uses Select to return only the fields required by the application instead of loading complete entity objects.

Detailed Explanation

Projection uses Select to return only the fields required by the application instead of loading complete entity objects.

This can reduce SQL result size, network transfer, memory usage, and change-tracking overhead. It also maps naturally to DTOs used by APIs or views.

For read-heavy endpoints, projection is often more efficient than Include when the application needs only a subset of entity and related data.

Code Example

var products = await _context.Products
    .AsNoTracking()
    .Where(p => p.IsActive)
    .Select(p => new ProductListDto
    {
        Id = p.Id,
        Name = p.Name,
        CategoryName = p.Category.Name,
        Price = p.Price
    })
    .ToListAsync();