如何将谓词与包含的属性一起包含在内?

2024-04-25

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

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() method.

我试图做这样的事情(这显然不起作用,因为你可以重新分配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();
           }
    }

您应该能够在调用中应用谓词Where之间Include and Load, 像这样:

foreach (var includedProperty in includeProperties)
{
     dbSet.Include(includedProperty).Where(predicate).Load();
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何将谓词与包含的属性一起包含在内? 的相关文章

随机推荐