EF Core and query boundaries
Make database work visible before optimizing it.
The idea
An IQueryable describes work that may not have executed yet. Filter by tenant before materializing results and project only the fields needed by the response. A read-only view often does not need tracking. Observe query counts so a loop cannot quietly become an N+1 query pattern.
Follow the flow
Make it concrete
This excerpt isolates the concept. Connect it to the booking API as you work through the exercise.
var rows = await db.Bookings
.AsNoTracking()
.Where(b => b.TenantId == tenantId)
.OrderBy(b => b.Id)
.Select(b => new BookingResponse(b.Id, b.Seats))
.Take(50)
.ToListAsync(ct);Decisions that matter
- Projection reduces transferred data and avoids unintentionally exposing persistence entities.
- Pagination requires a deterministic order; a unique tie-breaker prevents unstable pages.
- Use a real database integration test for SQL translation and provider behavior.
Your turn
A booking list loads its tenant separately for each of 50 rows. How would you prove and remove the extra round trips?
Reveal a worked answer
Record database commands in an integration test and inspect the generated SQL. Project the required tenant fields in one query or load a bounded batch. Verify tenant isolation and returned ordering after changing the query.