In this lesson, you will learn how to configure Entity Framework Core to automatically load related data only when you access a navigation property for the first time.
The Concept of Dynamic Proxies
By default, EF Core does not load related entities unless you use Include (Eager Loading) or Entry().Reference().Load() (Explicit Loading). Lazy Loading Proxies change this by creating a dynamic subclass of your entity at runtime. This subclass intercepts calls to navigation properties, checking if the data is already loaded; if not, it automatically triggers a database query to fetch it.
To enable this, you must install the Microsoft.EntityFrameworkCore.Proxies package and register it during your DbContext configuration:
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
=> optionsBuilder
.UseLazyLoadingProxies() // Enables the proxy feature
.UseSqlServer(connectionString);
Implementing Requirements
For the proxy generator to intercept your properties, two conditions must be met:
- All navigation properties must be marked as
virtual. - Your entity classes must be designed to be inheritable (not
sealed).
public class Author
{
public int Id { get; set; }
// Must be virtual to allow the proxy to override the getter
public virtual ICollection<Book> Books { get; set; }
}
The "N+1" Caution
While this makes your code look incredibly clean—allowing you to simply access author.Books deep inside your business logic—it hides database activity. If you loop through a list of 100 authors and access the Books property on each, EF Core will fire 100 separate queries. This is the classic "N+1" problem. Use lazy loading for convenience in simple scenarios, but always remain conscious of the hidden round-trips occurring behind the scenes. If you find yourself accessing related data in a loop, switch back to Eager Loading with Include to maintain application performance.
Key Takeaway: Lazy loading proxies transform navigation properties into "on-demand" data fetchers, but because they hide database queries, they require virtual properties and careful monitoring to avoid performance-killing N+1 query patterns.