Func<TObject, bool>是委托(delegate)
Expression<Func<TObject, bool>>是表達式
Expression編譯后就會變成delegate,才能運行。比如
Expression<Func<int, bool>> ex = x=>x < 100;
Func<int, bool> func = ex.Compile();
然后你就可以調用func:
func(5) //-返回 true
func(200) //- 返回 false
而表達式是不能直接調用的。
===========================
案例:不正確的查詢代碼造成的數據庫全表查詢。
//錯誤的代碼 Func<QuestionFeed, bool> predicate = null; if (type == 1) { predicate = f => f.FeedID == id && f.IsActive == true; } else { predicate = f => f.FeedID == id; } //_questionFeedRepository.Entities的類型為IQueryable<QuestionFeed> _questionFeedRepository.Entities.Where(predicate);
上面代碼邏輯是根據條件動態生成LINQ查詢條件,將Func類型的變量作為參數傳給Where方法。
實際上Where要求的參數類型是:Expression<Func<TSource, bool>>。
解決方法:
不要用Func<TSource, bool>,用Expression<Func<TSource, bool>>。
//正確的代碼 Expression<Func<QuestionFeed, bool>> predicate=null; if (type == 1) { predicate = f => f.FeedID == id && f.IsActive == true; } else { predicate = f => f.FeedID == id; } _questionFeedRepository.Entities.Where(predicate);