-
Notifications
You must be signed in to change notification settings - Fork 224
Lazy Loading
In Database.tt:
Settings.UseLazyLoading = true;This marks all navigation properties as virtual, which is required for lazy loading.
EF Core lazy loading requires the Microsoft.EntityFrameworkCore.Proxies package:
Install-Package Microsoft.EntityFrameworkCore.Proxies
Then configure the DbContext to use lazy loading proxies:
Via Program.cs / Startup.cs (recommended):
services.AddDbContext<MyDbContext>(options => options
.UseSqlServer(Configuration.GetConnectionString("DefaultConnection"))
.UseLazyLoadingProxies());Via OnConfiguring:
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
optionsBuilder
.UseSqlServer(@"...;MultipleActiveResultSets=True;...")
.UseLazyLoadingProxies();
}Also add MultipleActiveResultSets=True to the connection string.
Lazy loading is enabled by default when navigation properties are virtual. No additional packages are required. Add MultipleActiveResultSets=True to the connection string.
Web applications: Lazy loading is generally a poor choice for web APIs and MVC applications:
- Request contexts are short-lived; lazy loading can cause many extra database round-trips.
- Serialization of lazy-loaded entities can trigger queries that load the entire database.
- Use eager loading (
.Include(p => p.Address)) or explicit loading instead.
Serialization: If you serialize entities with JSON (e.g., System.Text.Json, Newtonsoft.Json), lazy-loaded navigation properties will be queried during serialization. Use [JsonIgnore] or DTOs to avoid this.
Settings.UseLazyLoading = false;Navigation properties are not marked virtual. Use .Include() for eager loading:
var orders = dbContext.Orders
.Include(o => o.Customer)
.Include(o => o.OrderItems)
.ToList();