[英]How to lazy load a where condition using LINQ
我是 LINQ 的新手
我试图where
使用延迟加载的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
列表
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 to entity 构建表达式树,当您从中请求实际数据时 - 它会将您的请求应用于数据库并返回结果。 所以默认是延迟加载。
var request = DbContext.Animal.AsQeriable();
if (predicate != null)
request = request.Where(predicate);
return request.Count();
你也可以接受你的谓词的 params 数组作为
Foo(params Expression<Func<Animal, bool>>[] predicates)
然后像这样在你的函数中使用它们:
foreach(var predicate in predicates)
request = request.Where(predicate);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.