
Lazy loading
You load related entities on demand rather loading at once. This approach is usually useful when you want to load related entities on a certain condition (otherwise always use eager loading).
To enable lazy loading, you need to install this package: Microsoft.EntityFrameworkCore.Proxies
And do following changes in Program.cs
builder.Services.AddDbContext<AppDbContext>(o=>o.UseLazyLoadingProxies()
.UseSqlite("Data Source = mydb.db"));
Look at the example below:
app.MapGet("/", async (AppDbContext context) => {
foreach (var genre in await context.Genres.ToListAsync())
{
foreach (var book in genre.Books)
{
Console.WriteLine($"===> genre: {genre.Name}, Book: {book.Title}, Price : {book.Author}");
}
}
return Results.Ok("Ok");
});
We are not loading books with genres at once. Rather we are loading books for each genres. Let’s take a look at logs of console.










