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

Explicit Loading Techniques

Load navigation properties on-demand after initial query execution for optimized resource usage.

In this lesson, you will learn how to manually load related data for an entity only when your application logic determines it is strictly necessary, saving database bandwidth.

The Concept of Explicit Loading

So far, you have used Eager Loading (Include) to fetch related data during the initial database query. While efficient for data you know you need, it can be wasteful if you only need the related data under specific conditions. Explicit Loading allows you to keep your initial query light and perform a follow-up query to retrieve navigation properties only when required.

This technique is particularly useful in long-running processes or complex conditional logic where loading extra data upfront would be redundant.

Implementing Explicit Loading

To explicitly load a property, you use the Entry() method on your DbContext to access the entry of the loaded entity. From there, you target the specific navigation property you wish to populate.

Consider a scenario where we retrieve a Student but only fetch their Courses if a specific flag is set:

// 1. Initial query: No courses are loaded yet
var student = await context.Students.FirstOrDefaultAsync(s => s.Id == 1);

// 2. Conditional check: Only load data if necessary
if (needsCourseDetails)
{
    // The Load() method executes a separate query to populate the collection
    await context.Entry(student)
                 .Collection(s => s.Courses)
                 .LoadAsync();
}

// 3. For a single reference (not a collection), use Reference()
await context.Entry(student)
             .Reference(s => s.Profile)
             .LoadAsync();

Why Use This?

The main advantage here is granular control. By separating the retrieval of the main entity from the retrieval of its relationships, you prevent the "cartesian product" issue that can sometimes arise with complex Include chains, and you avoid downloading large graphs of data that your user may not actually end up viewing.

Keep in mind that each Load() call triggers an additional trip to the database. Ensure you use this technique sparingly to avoid the "N+1 query problem" inside loops.

Key Takeaway: Explicit Loading defers the retrieval of related data until the precise moment it is needed, allowing you to optimize performance by fetching only the data your current business logic requires.