[英]How to lazy load a where condition using LINQ
I'm new to LINQ我是 LINQ 的新手
I'm trying to execute a dynamic where
using the lazy loading, but I can't understand how to do it.我试图
where
使用延迟加载的where
执行动态,但我不明白该怎么做。
This is my code这是我的代码
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();
}
Now, the problem is that the query is very slow, I think it's because the where clause are applied on the SELECT * FROM Animal
list queried现在,问题是查询很慢,我认为是因为where子句应用于查询的
SELECT * FROM Animal
列表
System.Linq.Expression<System.Func<Animal, bool>>
instead of System.Func<Animal, bool>
, this is required for use with EF and I am assuming you want the expressions applied as SQL and not in memory.System.Linq.Expression<System.Func<Animal, bool>>
而不是System.Func<Animal, bool>
,这是与 EF 一起使用所必需的,我假设您希望将表达式应用为 SQL 而不是在记忆中。params
and an array of expressions and then iterate over them to apply them.params
和表达式数组,然后迭代它们以应用它们。 Changed code:更改的代码:
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 builds the expression tree and when you request the actual data from it - it applies your request against the database and returns the result. Linq to entity 构建表达式树,当您从中请求实际数据时 - 它会将您的请求应用于数据库并返回结果。 So it's a lazy loading by default.
所以默认是延迟加载。
var request = DbContext.Animal.AsQeriable();
if (predicate != null)
request = request.Where(predicate);
return request.Count();
You could also go with accepting params array of your predicates as你也可以接受你的谓词的 params 数组作为
Foo(params Expression<Func<Animal, bool>>[] predicates)
And then use them inside your function like this:然后像这样在你的函数中使用它们:
foreach(var predicate in predicates)
request = request.Where(predicate);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.