Tutorials Entity Framework Core Tutorial
Lazy Loading in EF Core
Lazy Loading in EF Core: free step-by-step lesson with examples, common mistakes, and interview tips — part of Entity Framework Core Tutorial on Toolliyo Academy.
On this page
Entity Framework Core Tutorial · Lesson 46 of 100
Lazy Loading in EF Core
Beginner ✓ → Intermediate ✓ → Advanced → Professional
Advanced · 3 — Production skills · ~6 min · Module 5: Relationships
What is this?
Lazy loading automatically loads navigations when accessed on tracked entities — enabled via proxy package and virtual navigations or ILazyLoader injection.
Why should you care?
Legacy ShopNest admin tools may touch order.Customer.Name deep in views — lazy load defers queries until access (use sparingly in APIs).
See it live — copy this example
Paste into a .NET project with EF Core packages, then run with LocalDB/SQL Server (dotnet ef / dotnet run).
// Program.cs
options.UseLazyLoadingProxies();
// Entity:
public virtual Customer Customer { get; set; } = null!;
// Usage (tracked entity):
var order = await _context.Orders.FindAsync(10);
Console.WriteLine(order.Customer.Email); // triggers SELECT Customer
What happened?
- Proxy wraps entity — first access to Customer fires lazy loader query.
- Requires virtual navigations and context still alive — dangerous in APIs after dispose.
Practice next
- Add Microsoft.EntityFrameworkCore.Proxies package.
- Mark navigations virtual on entities using lazy load.
- Enable UseLazyLoadingProxies in DbContext options.
- Disable lazy loading and compare SQL query count in logs for same code path.
- Inject ILazyLoader manually instead of virtual proxies.
Remember
Lazy load queries on first navigation access. Needs proxies and alive DbContext. Avoid in Web API JSON serialization.
ShopNest legacy admin refactor
Old WinForms admin relied on lazy load; new API replaces with explicit Include.
Outcome: N+1 eliminated — product listing API response time drops 80%.
Interview prep for this lesson
Practice these questions aloud after reading—each links to a full structured answer.
Sign in to ask a question or upvote helpful answers.
No questions yet — be the first to ask!