Entity Framework Core Interview Question #50
What are best practices for relationships and loading related data in EF Core?
Relationships, Navigation Properties & Loading Data Junior Beginner
Quick Interview Answer
Model relationships according to real business rules and make principal/dependent roles, requiredness, foreign keys, and delete behavior clear. Use explicit Fluent API configuration where conventions are ambiguous.
Detailed Explanation
Model relationships according to real business rules and make principal/dependent roles, requiredness, foreign keys, and delete behavior clear. Use explicit Fluent API configuration where conventions are ambiguous.
Choose loading strategies deliberately. Use projection for read-only screens and APIs when only selected fields are required, eager loading when an entity graph is genuinely needed, and explicit loading when conditional loading is appropriate. Treat lazy loading carefully because hidden queries can create N+1 problems.
Monitor generated SQL, avoid unnecessarily large graphs, use split queries when they solve measured cartesian-expansion problems, and ensure indexes exist on important foreign-key and filtering columns.
Code Example
var orders = await db.Orders
.AsNoTracking()
.Where(o => o.Status == OrderStatus.Open)
.Select(o => new OrderListDto
{
Id = o.Id,
CustomerName = o.Customer.Name,
ItemCount = o.Items.Count
})
.Take(50)
.ToListAsync(cancellationToken);