Exercise 1: EF Core Optimization
Objective
Fix N+1 problems and optimize queries
Task
Given a slow endpoint, optimize it:
// Slow version
var orders = await context.Orders.ToListAsync();
foreach (var order in orders)
{
order.Customer = await context.Customers.FindAsync(order.CustomerId);
order.Items = await context.OrderItems.Where(i => i.OrderId == order.Id).ToListAsync();
}
Solutions to Implement
- Eager loading with Include
- Projection with Select
- Split queries for multiple collections
- AsNoTracking for read-only
- Compiled queries
Expected Outcome
- 10x+ performance improvement
- Understanding of query execution