ASP.NET Core Web API Interview Question #114

What is eager loading with Include in EF Core?

Dependency Injection, Services, EF Core, Async & Data Access Mid-Level Intermediate

Quick Interview Answer

Eager loading retrieves related data as part of a query using Include and ThenInclude. It is useful when the application genuinely needs related entities as entities.

Detailed Explanation

Eager loading retrieves related data as part of a query using Include and ThenInclude. It is useful when the application genuinely needs related entities as entities.

For API read models, projection is often preferable because it retrieves only required fields. Large Include graphs can produce expensive SQL or excessive result data.

Code Example

var order = await _db.Orders
    .Include(o => o.Items)
    .ThenInclude(i => i.Product)
    .SingleOrDefaultAsync(o => o.Id == id, token);