Related Data Loading using EF Core – Part 1
In few of previous posts we have seen how Transaction management can be handled using EF Core. Let’s now understand different ways by which data can be loaded using EF Core.
There are basically 3 common patterns to load the related data.
1. Eager Loading
2. Explicit Loading
3. Lazy Loading
This is Part 1 of related Data Loading patterns and we will cover Eager Loading in this part.
Eager Loading in EF Core :
Eager Loading is a pattern of loading related data along with the main entity. This means that the main entity and related data can be fetched using a single query saving the time and bandwidth.
Eager Loading is done using the “.Include()” method as shown in following example :
using (DBEntities context = new DBEntities())
{
var employees = context.Employees.Include(x => x.EmpDetails). ToList();
foreach (var emp in employees)
{
string EmpName = emp.Name;
string EmpCode = emp.Code;
string EmpAddress = emp.EmpDetails.Address;
}
}
Eager Loading using “.AutoInclude()” method is introduced in EF Core 6.0 :
Auto Include helps include the related data every time the entity gets loaded. It has same effect as calling “.Include()” in every query to get the results as shown in following example :
modelBuilder.Entity<Employees>().Navigation(e =>
e.EmpDetails).AutoInclude();