How to use Generic Repository Multiple Includes in C#

By FoxLearn 2/16/2024 3:09:32 PM   114
This post shows you how to use Generic Repository Multiple Includes using Entity Framework in C#

Creating an IRepository 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 that inherits from IRepository

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();
    }    
}

To call method you can use as shown below

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

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