Related Data Loading using EF Core – Part 2

Related Data Loading using EF Core – Part 2

Related Data Loading using EF Core

In part 1 of related data loading series we have seen how Eager Loading works. This is part 2 of the series and we will cover Explicit Loading in this part.

Explicit Loading in EF Core :

Explicit Loading is a technique of loading related data entities with an explicit call. It means that the related data is explicitly loaded from the database at a later time. In order to load a related entity we make an explicit call to Load method of the related entity’s DbContext.Entry(…) object.

First we use the DbContext.Entry method to gain access to a tracked entity in order to invoke the Load method. From this Entry, we can use the Reference or Collection method to get the reference to that navigational property to call the Load method to get the data from the database.

Here is the reference code to understand this better:

using (DBEntities context = new DBEntities())

{

var employees = context.Employees.ToList();

foreach (var emp in employees)

{

context.Entry(emp).Reference(x => x.EmpDetails).Load();

}

}

Loading Collections :

In case,If the navigation property is of reference type we use the reference method. For collection navigation property, the collection method is to be used.

Here is the reference code to understand this better:

using (DBEntities context = new DBEntities())

{

var employees = context.Employees.ToList();

foreach (var emp in employees)

{

context.Entry(emp).Collection(x => x.EmpSalaryStructure).Load();

}

}

Share this post