Expression >與Func 的區別


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);

  

  


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM