使用 Entity Framework 最要小心的性能殺手就是 —— 不正確的查詢代碼造成的數據庫全表查詢。
我們就遇到了一次,請看下面的示例代碼:
//錯誤的代碼
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>>。
寫代碼時沒注意這個問題,運行結果也正確。發布后,在SQL Server Profiler監測中,發現QuestionFeed對應的數據庫表出現了全表查詢,才知道這個地方的問題。
問題就是:
將Func類型的變量作為參數傳給Where方法進行LINQ查詢時,Enitity Framework會產生全表查詢,將整個數據庫表中的數據加載到內存,然后在內存中根據Where中的條件進一步查詢。
解決方法:
不要用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);