Roadmap › Entity Framework (EF6 & EF Core) › Module: Querying
Lessons in this course (15)
8. Loading related data: eager, explicit, lazy
Intermediate★ Must knowLesson 8 of 15
csharp
// Eager loading
var orders = await db.Orders
.Include(o => o.Customer)
.Include(o => o.Lines.Where(l => l.Qty > 0)) // filtered include (EF 5)
.ThenInclude(l => l.Product)
.AsSplitQuery() // avoid cartesian explosion with multiple collections
.ToListAsync();
// Explicit loading
var customer = await db.Customers.FirstAsync(c => c.Id == id);
await db.Entry(customer).Collection(c => c.Orders).LoadAsync();
await db.Entry(order).Reference(o => o.Customer).LoadAsync();
// Lazy loading (opt-in): Microsoft.EntityFrameworkCore.Proxies + UseLazyLoadingProxies(); virtual navigations| When loaded | Risk | |
|---|---|---|
Eager (Include) | Same query | Cartesian explosion with several collections → AsSplitQuery |
| Explicit | When you call Load | Extra round trips, but controlled |
| Lazy | On first access of navigation | N+1 queries, hidden DB calls, serialisation loops |