如何使用 LINQ 延迟加载 where 条件
How to lazy load a where condition using LINQ
我是 LINQ 新手
我正在尝试使用延迟加载执行动态 where
,但我不明白该怎么做。
这是我的代码
protected int AnimalCount(System.Func<Animal, bool> expression = null, System.Func<Animal, bool> additionalExpression= null)
{
var records = (from temp in DbContext.Animal select temp);
if (expression != null) records = records.Where(expression).AsQueryable();
if (additionalExpression != null) records = records.Where(additionalExpression).AsQueryable();
return records.Count();
}
现在,问题是查询很慢,我认为这是因为 where 子句应用于 SELECT * FROM Animal
列表查询
Linq to entity 构建表达式树,当您从中请求实际数据时 - 它会将您的请求应用于数据库并 returns 结果。所以默认是懒加载。
var request = DbContext.Animal.AsQeriable();
if (predicate != null)
request = request.Where(predicate);
return request.Count();
您也可以接受谓词的参数数组作为
Foo(params Expression<Func<Animal, bool>>[] predicates)
然后像这样在你的函数中使用它们:
foreach(var predicate in predicates)
request = request.Where(predicate);
- 您应该使用
System.Linq.Expression<System.Func<Animal, bool>>
而不是 System.Func<Animal, bool>
,这是与 EF 一起使用所必需的,我假设您希望将表达式应用为 SQL 而不是在内存中。
- 您可以更改签名以使用
params
和一组表达式,然后迭代它们以应用它们。
更改代码:
protected int AnimalCount(params System.Linq.Expression<System.Func<Animal, bool>>[] expressions)
{
var records = DbContext.Animal as IQueryable<Animal>;
foreach (var expression in expressions)
records = records.Where(expression);
return records.Count();
}
我是 LINQ 新手
我正在尝试使用延迟加载执行动态 where
,但我不明白该怎么做。
这是我的代码
protected int AnimalCount(System.Func<Animal, bool> expression = null, System.Func<Animal, bool> additionalExpression= null)
{
var records = (from temp in DbContext.Animal select temp);
if (expression != null) records = records.Where(expression).AsQueryable();
if (additionalExpression != null) records = records.Where(additionalExpression).AsQueryable();
return records.Count();
}
现在,问题是查询很慢,我认为这是因为 where 子句应用于 SELECT * FROM Animal
列表查询
Linq to entity 构建表达式树,当您从中请求实际数据时 - 它会将您的请求应用于数据库并 returns 结果。所以默认是懒加载。
var request = DbContext.Animal.AsQeriable();
if (predicate != null)
request = request.Where(predicate);
return request.Count();
您也可以接受谓词的参数数组作为
Foo(params Expression<Func<Animal, bool>>[] predicates)
然后像这样在你的函数中使用它们:
foreach(var predicate in predicates)
request = request.Where(predicate);
- 您应该使用
System.Linq.Expression<System.Func<Animal, bool>>
而不是System.Func<Animal, bool>
,这是与 EF 一起使用所必需的,我假设您希望将表达式应用为 SQL 而不是在内存中。 - 您可以更改签名以使用
params
和一组表达式,然后迭代它们以应用它们。
更改代码:
protected int AnimalCount(params System.Linq.Expression<System.Func<Animal, bool>>[] expressions)
{
var records = DbContext.Animal as IQueryable<Animal>;
foreach (var expression in expressions)
records = records.Where(expression);
return records.Count();
}