0

I wrote a generic repo method including all the navigation properties as following:

    public async Task<IEnumerable<T>> GetAllWhereAsync(Expression<Func<T, bool>> expression, bool include = false)
    {
        if (include)
            foreach (var name in _db.Model.FindEntityType(typeof(T)).GetNavigations().Select(e => e.Name))
                _db.Set<T>().Include(name).Load();

        return await _db.Set<T>().AsNoTracking().Where(expression).ToListAsync();
    }

However, when I call this method, my resulting entities don't have their navigation property included. What should I do?

M. Azyoksul
  • 1,580
  • 2
  • 16
  • 43
  • `Include()` calls need to be chained together and the same `IQueryable` used in the `return`. LINQ in general is immutable and returns new query objects even from things which appear to modify the query. – Tanveer Badar Jun 19 '20 at 15:33

1 Answers1

1

See if this modification compiles, I am no where near a compiler right now so can't be sure.

public async Task<IEnumerable<T>> GetAllWhereAsync(Expression<Func<T, bool>> expression, bool include = false)
{
    var query = _db.Set<T>();
    if (include)
        foreach (var name in _db.Model.FindEntityType(typeof(T)).GetNavigations().Select(e => e.Name))
            query = query.Include(name);

    return await query.AsNoTracking().Where(expression).ToListAsync();
}
Tanveer Badar
  • 5,438
  • 2
  • 27
  • 32
  • query is actually a DbSet here so I get Cannot implicitly convert type 'System.Linq.IQueryable' to 'Microsoft.EntityFrameworkCore.DbSet' **Edit:** var query = _db.Set().AsQueryable(); works. Thanks. – M. Azyoksul Jun 19 '20 at 15:40