[英]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.