Explicit Loading Related Entities

Here you will learn how to load related entities in an entity graph explicitly. Explicit loading shown in this chapter are valid in EF 6 and EF Core both.

Even with lazy loading disabled (in EF 6), it is still possible to lazily load related entities, but it must be done with an explicit call. Use DbContext.Entry(..) API to accomplish this.

using (var context = new SchoolContext())
{
    var student = context.Students
                        .Where(s => s.FirstName == "Bill")
                        .FirstOrDefault<Student>();

    context.Entry(student).Reference(s => s.Address).Load(); // loads StudentAddress 
    context.Entry(student).Collection(s => s.StudentCourses).Load(); // loads StudentCourses collection 
}     

As you can see above, use Reference() method to specify the reference navigation property to be loaded and Collection() method to specify the collection navigation property. The .load() will execute the SQL query in the database to get the data and fill up the specified reference or collection property of an entity in the memory as shown below.

Entity Framework tutorial 4.3 dbcontext

Querying Related Entities:

You can also write LINQ-to-Entities queries to filter the related data before loading. The Query() method enables us to write further LINQ queries for the related entities to filter out related data.

using (var context = new SchoolContext())
{
    var student = context.Students
                        .Where(s => s.FirstName == "Bill")
                        .FirstOrDefault<Student>();
    
    context.Entry(student).Collection(s => s.StudentCourses)
                          .Query().Where(sc => sc.CourseName == "Maths").FirstOrDefault();
}     

In the above example, .Collection(s => s.Courses).Query() allow use to write further queries on StudentCourses.