Search code examples
c#asp.netentity-frameworkeager-loading

Generic repository with eager load using ThenInclude() method?


Here is my generic repository:

public class Repository<T> : IRepository<T> where T : BaseEntity
{
    private DbContext _dbContext { get; set; }
    private DbSet<T> _dbSet { get; set; }

    public Repository(DbContext context)
    {
        this._dbContext = context;
        this._dbSet = context.Set<T>();
    }

    public IQueryable<T> GetAll(params Expression<Func<T, object>>[] includes)
    {
        IQueryable<T> currentSet = this._dbSet;
        foreach (var item in includes)
        {
            currentSet = currentSet.Include(item);
        }
        return currentSet;
    }

    public T Get(Expression<Func<T, bool>> predicated, 
        params Expression<Func<T, object>>[] includes) 
        => this.GetAll(includes).Where(predicated).FirstOrDefault();
}

and the problem is when I am using eager loading to load a question(include it's answers) then I can't query votes of answers.

I reliazed I got this error because I am loading a question include it's answers and include answers's vote again. So I try to using ThenInclude() to solve this problem but I have no idea how to apply it in generic repository.

Any help really appreciated.

Thanks


Solution

  • You can using nested include to solve your problem. Reference link: EF LINQ include multiple and nested entities