lim*_*dev 3 c# linq lazy-loading
我是 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();
}
Run Code Online (Sandbox Code Playgroud)
现在,问题是查询很慢,我认为是因为在SELECT * FROM Animal查询的列表上应用了where子句
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();
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
243 次 |
| 最近记录: |