4

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

Tấn Sang
  • 1,375
  • 9
  • 21
  • First ask yourself the question whether you *really* need this repository layer. Usually it only causes trouble. Do you *really* lose anything when you remove them and work with DbSets directly? – Gert Arnold Mar 10 '18 at 21:17
  • The main reason why I adding repository implementation to my project is using dependency injection and make my code more testable. – Tấn Sang Mar 11 '18 at 06:33
  • 1
    Is it worth the imposed limitations though? Anyway, maybe [this](https://stackoverflow.com/a/47063432/861716) will help. – Gert Arnold Mar 11 '18 at 14:23
  • @GertArnold I am also using a generic repository for the same reason as OP. Can you please help providing some links to understand what you said in your previous comment? – Dipendu Paul Sep 26 '20 at 03:36

1 Answers1

0

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

Phú Dnp
  • 74
  • 5
  • This is a link-only answer, making it useless when the link breaks. Moreover, you refer to an EF6 solution which absolutely doesn't work in EF-core that OP is working in. I wonder why it was accepted. – Gert Arnold Mar 21 '18 at 11:07