如何将谓词与 Included 属性一起包含?

How can I include a predicate along with Included properties?

目前,我有一个功能允许我查询数据库,同时在结果中包含一些其他相关表,以防止 return 命中数据库,如果我不这样做,我知道会发生这种情况:

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

但是,我还需要能够在包含之前使用 where 子句,以便它在触发 Load() 方法时不会尝试查询整个数据库。

我正在尝试做这样的事情(这显然行不通,因为您可以像下面的示例代码一样重新分配 dbset)。

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

您应该能够在 IncludeLoad 之间对 Where 的调用中应用谓词,如下所示:

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

您可以使用 LinqKit library. Download the nuget packageAsExpandable 扩展方法:

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