Eager Loading In Repository Pattern Entity Framework Core

In this blog, we will learn Eager Loading In Repository Pattern Entity Framework Core

Introduction

 
Eager loading is the process whereby a query for one type of entity also loads related entities as part of the query, so that we don't need to execute a separate query for related entities.
 
In simple language, Eager loading joins the entities which have foreign relation and returns the data in a single query.
 
Now, the question is how to properly handle the eager-loading problem for complex object graphs within the Repository pattern.
 
Let's get started.
 
Step 1:  Add a method into your Interface which eager loads the entities which we specify:
  1. public interface IProjectInterface<T> where T : class  
  2. {  
  3. Task<IEnumerable<T>> EntityWithEagerLoad(Expression<Func<T, bool>> filter,                string[] children);  
  4. Task<List<T>> GetModel();  
  5. T GetModelById(int modelId);  
  6. Task<bool> InsertModel(T model);  
  7. Task<bool> UpdateModel(T model);  
  8. Task<bool> DeleteModel(int modelId);  
  9. void Save();  

The method EntityWithEagerLoad() takes 2 arguments, one is filter criteria and another is an array of entities which we want to eager load.
 
Step 2: Define the method EntityWithEagerLoad in your base repository:
  1. public async Task<IEnumerable<T>> EntityWithEagerLoad(Expression<Func<T, bool>> filter, string[] children)  
  2. {  
  3.             try  
  4.             {  
  5.                 IQueryable<T> query = dbEntity;  
  6.                 foreach (string entity in children)  
  7.                 {  
  8.                     query = query.Include(entity);  
  9.   
  10.                 }  
  11.                 return await query.Where(filter).ToListAsync();  
  12.             }  
  13.             catch(Exception e)  
  14.             {  
  15.                 throw e;  
  16.             } 
Step 3 : For using this method , call this function from your controller as shown  below:
  1. [HttpGet]  
  2.        [Route("api/Employee/getDetails/{id}")]  
  3.        public async Task<IEnumerable<string>> GetDetails([FromRoute]int id)  
  4.        {  
  5.            try  
  6.            {  
  7.       var children = new string[] { "Address", “Education” };  
  8.   
  9.       var employeeDetails=await _repository.EntityWithEagerLoad (d => d.employeeId==id,  
  10.       children);  
  11.   
  12.            }  
  13.            catch(Exception e)  
  14.            {  
  15.                Throw e;              
  16.            } 
The variable employeeDetails contains employee details with their Address and education details.