-
Notifications
You must be signed in to change notification settings - Fork 226
Lazy Loading
Lazy loading is off in the shipped Database.tt (Settings.UseLazyLoading = false). To turn it on:
Settings.UseLazyLoading = true;This marks all navigation properties as virtual, which is required for lazy loading. On its own that is not
enough for EF Core - see the next section.
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();- Home
- Compared with the Microsoft scaffolder
- Connection strings
- JetBrains Rider
- Upgrading from v3 to v4
- Saving .tt does nothing
- Settings A-Z - every setting, with a page each
- Common Settings Types Explained
- Settings Callbacks
- Settings runtime values and helpers
- Filtering
- Full Control Over the Generated Code
- Enum Generation from Table Data
- Owned Entities
- JSON column support
- Global Query Filters
- Extended Property Names Feature
- Partial Properties
- File-Scoped Namespaces
- Data Annotations
- Spatial Types
- HierarchyId
- RowVersion and TimeStamp columns
- Lazy Loading
- Stored proc result sets