DEV Community

Cover image for Loading Techniques in EF Core
Shreyans Padmani
Shreyans Padmani

Posted on

Loading Techniques in EF Core

Working with Entity Framework Core? Knowing how data is loaded can drastically affect your app's performance. Here's a breakdown of the three key loading techniques:

Lazy Loading

  • Loads related data only when the navigation property is first accessed.
  • Reduces initial query load by delaying related data fetching.
  • Requires navigation properties to be marked as virtual.
  • Needs Microsoft.EntityFrameworkCore.Proxies and .UseLazyLoadingProxies() enabled.
  • Can lead to N+1 query issues if overused.
  • Improves performance when related data is rarely needed.
  • Ideal for large datasets with optional relationships.
  • Not supported in all scenarios like DTOs or projections.

Eager Loading

  • Loads related data along with the main entity in a single query.
  • Achieved using the .Include() and .ThenInclude() methods.
  • Reduces round-trips by fetching all required data upfront.
  • Useful when related data is always needed immediately.
  • Can fetch multiple levels of related entities using chaining.
  • Improves performance by avoiding lazy load triggers.
  • May fetch unnecessary data if not carefully planned.
  • Ideal for read-heavy scenarios with known data requirements.
  • Simplifies the code logic by avoiding the need to manually load or loop for related collections later.

Explicit Loading

  • Explicit loading loads related data only when you specifically request it using .Load() method.
  • Useful when you don’t want automatic loading of navigation properties.
  • Provides full control over when and what related data is fetched.
  • Reduces unnecessary data transfer, ideal for fine-tuned performance.
  • Use context.Entry(entity).Reference().Load() for single navigation properties.
  • Use context.Entry(entity).Collection().Load() to load related collections manually.
  • Works well in disconnected scenarios or with detached entities.
  • Avoids N+1 issues common with lazy loading by controlling query execution.
  • Helps load specific data after checking business logic or conditions.
  • More verbose than eager loading but precise and performance-friendly when used right.

Coclusion

Choosing the right loading technique in EF Core—Lazy, Eager, or Explicit—can significantly impact your application’s performance and maintainability. Lazy is demand-based, Eager loads upfront, and Explicit gives precise control. Use them wisely based on data access patterns to ensure efficient, scalable, and clean data handling in your applications.

Top comments (0)