ASP.NET Core Web API Interview Question #112
Why should API queries project directly to DTOs?
Dependency Injection, Services, EF Core, Async & Data Access Mid-Level Intermediate
Quick Interview Answer
Projection selects only the fields required by the response and lets EF Core translate that shape into SQL. It can reduce transferred columns, memory use, entity tracking, and accidental exposure of internal data.
Detailed Explanation
Projection selects only the fields required by the response and lets EF Core translate that shape into SQL. It can reduce transferred columns, memory use, entity tracking, and accidental exposure of internal data.
For read endpoints, projecting directly to response DTOs is often more efficient than loading full entity graphs and mapping them afterward.
Code Example
var products = await _db.Products
.AsNoTracking()
.Select(x => new ProductResponse
{
Id = x.Id,
Name = x.Name,
Price = x.Price
})
.ToListAsync(token);