How to include a predicate with included properties?

I currently have a function that allows me to query the database, including some other related tables in the results, to prevent it from getting back into the database, which, as I know, will happen differently if I do not:

public class EntityRepository<TEntity> : IEntityRepository<TEntity> where TEntity : class
{
    protected DbSet<TEntity> dbSet;

    private readonly DbContext dc;

    public EntityRepository()
    {
        dc = new DbContext(Utility.Config.GetEntityDbConnection());
        dbSet = dc.Set<TEntity>();
    }


    public IQueryable<TEntity> GetAllIncluding(params Expression<Func<TEntity, object>>[] includeProperties)
    {
            foreach (var includedProperty in includeProperties)
            {
                dbSet.Include(includedProperty).Load();
            }

            return dbSet;
    }
}

However, I need to also use the where clause before turning it on so that it does not try to query the entire database when the method starts Load().

I tried to do something like this (which obviously does not work, because you can reassign dbset, as in my code example below).

    public IQueryable<TEntity> SearchForIncluding(Expression<Func<TEntity, bool>> predicate, params Expression<Func<TEntity, object>>[] includeProperties)
    {
           dbset = dbSet.Where(predicate);  //THIS DOESN'T WORK OBVIOUSLY

           foreach (var includedProperty in includeProperties)
           {
                dbSet.Include(includedProperty).Load();
           }
    }
+4
source share
2 answers

LinqKit. nuget AsExpandable:

public IQueryable<TEntity> SearchForIncluding(Expression<Func<TEntity, bool>> predicate, params Expression<Func<TEntity, object>>[] includeProperties)
{
        IQueryable<TEntity> query = dbSet;

        if (includeProperties != null)
        {
            query = includeProperties.Aggregate(query, (current, include) => current.Include(include));
        }
        if (predicate != null)
        {
            query = query.AsExpandable().Where(predicate);
        }
        return query;
}
+1

Where Include Load, :

foreach (var includedProperty in includeProperties)
{
     dbSet.Include(includedProperty).Where(predicate).Load();
}
+3

All Articles