How to use Generic Repository Multiple Includes in C#

By FoxLearn 8/1/2024 2:34:17 AM   324
Using a Generic Repository pattern with Entity Framework (EF) can help to abstract and centralize data access logic in your application.

When you need to include multiple related entities in your queries, the approach involves configuring the repository to handle Include statements dynamically.

Start by defining the interface for your generic repository as shown below.

public interface IRepository<T> where T : class
{
    Task<IList<T>> GetListApplyEagerLoadingAsync(params Expression<Func<T, object>>[] childrens);
}

Next, You need to create a BaseRepository class.

Implement the repository using Entity Framework’s DbContext. The implementation should handle the inclusion of related entities.

public abstract class BaseRepository<T> : IRepository<T> where T : class
{
    private readonly ApplicationDbContext _dataContext;
    protected DbSet<T> DbSet { get; set; }

    public BaseRepository(ApplicationDbContext dataContext)
    {
        _dataContext = dataContext;
        DbSet = _dataContext.Set<T>();
    }

    public async virtual Task<IList<T>> GetListApplyEagerLoadingAsync(params Expression<Func<T, object>>[] childrens)
    {
        childrens.ToList().ForEach(x => DbSet.Include(x).Load());
        return await DbSet.ToListAsync();
    }    
}

You can now use this generic repository to fetch entities with multiple includes.

Here’s an example of how to call method.

gridControl.DataSource = await _unitOfWork.User.GetListApplyEagerLoadingAsync(r => r.Roles);

The idea is to have one Generic Repository that will work with all entities.