2010-02-09 68 views
3

我敢肯定,這個問題的答案是:「你不能這樣做」或「不,不,你誤會......」,而是:LINQ到SQL編寫翻譯功能

我有一個LINQ類的事情,這會很樂意執行此:

var thingsWithAandB = from t in db.things 
         where t.propA.HasValue && t.propB.HasValue 
         select t; 

但我這個做了很多,所以我想:

partial class thing 
{ 
    public bool hasAandB 
    { 
     get 
     { 
      return propA.HasValue && propB.HasValue; 
     } 
    } 
} 

然後:

var thingsWithAandB = from t in db.things where t.hasAandB select t; 

但當然,當我這樣做時,我得到「無法將其轉化爲SQL」錯誤。我知道這是因爲在SQL查詢中調用方法是不可能的,因爲我的代碼和數據庫是分開的。

這是怎麼回事?這是不可能的嗎?

回答

-1

您可以使用擴展方法:

public static class MyExtensions{ 
    public static bool HasAandB(this thing t){ 
     return t.propA.HasValue && t.propB.HasValue; 
    } 
} 

,然後使用它:

var thingsWithAandB = from t in db.things 
        where t.HasAandB() 
        select t; 

編輯
對不起,這將可能給你同樣的例外。 ..

+0

我只是嘗試使用擴展方法,並獲得相同的'方法'布爾HasAandB(東西)'沒有支持轉換到SQL。 「錯誤... – Greg 2010-02-09 15:58:00