目前我有一个函数允许我查询数据库,同时在结果中包含一些其他相关表,以防止返回数据库,如果我不知道会发生这种情况:
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;
}
}
但是,我还需要在include之前使用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();
}
}
答案 0 :(得分:3)
您应该能够在Where
和Include
之间的Load
调用中应用谓词,如下所示:
foreach (var includedProperty in includeProperties)
{
dbSet.Include(includedProperty).Where(predicate).Load();
}
答案 1 :(得分:1)
您可以使用LinqKit库。下载nuget package并使用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;
}