Course contentsShow
← C#
Lesson 1131 of 1,90810. Entity Framework Core ModelingFree lesson

Optimizing Navigation Loading

Choose between eager, explicit, and lazy loading based on current operational requirements.

In this lesson, you will learn how to select the right strategy for loading related data to balance application performance and memory usage.

When working with navigation properties in Entity Framework Core, loading too much data results in bloated memory usage, while loading too little results in the infamous "N+1 query problem." Choosing the right loading strategy depends on your specific operational requirements.

1. Eager Loading (Include)

Use eager loading when you know you will definitely need the related data immediately. By using .Include(), EF Core generates a JOIN to fetch the entity and its related data in a single database round-trip.

var orders = context.Orders
    .Include(o => o.Customer)
    .ToList();
  • Best for: High-performance scenarios where you want to minimize round-trips and avoid the N+1 problem.
  • Trade-off: If you include too many relationships, you risk "Cartesian explosion," where the database returns redundant data, potentially slowing down the query.

2. Explicit Loading

Explicit loading is used when you have already loaded an entity and decide, based on specific logic, that you need to pull in related data later.

var order = context.Orders.First();
// Only load customers if a certain business condition is met
if (needsCustomerDetails) {
    context.Entry(order).Reference(o => o.Customer).Load();
}
  • Best for: Reducing the initial payload size. Use this when the related data is optional or conditional.

3. Lazy Loading

Lazy loading automatically fetches related data the moment you access the navigation property in your code. To use this, your navigation properties must be marked as virtual and your context configured accordingly.

  • Best for: Rapid prototyping or scenarios where access patterns to navigation properties are highly unpredictable.
  • Trade-off: This is the most common cause of performance degradation in production. Because it fires a new database query for every property access, it can silently cripple your database performance if used inside a loop.

Key Takeaway: Prioritize Eager Loading for predictable access patterns to avoid the N+1 problem, use Explicit Loading for conditional data fetching, and avoid Lazy Loading in performance-critical paths.