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();
  10. }
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. return await query.Where(filter).ToListAsync();
  11. }
  12. catch(Exception e)
  13. {
  14. throw e;
  15. }
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. var employeeDetails=await _repository.EntityWithEagerLoad (d => d.employeeId==id,
  9. children);
  10. }
  11. catch(Exception e)
  12. {
  13. Throw e;
  14. }
The variable employeeDetails contains employee details with their Address and education details.