2009-04-15 166 views
3
和擴展方法

我的擴展方法是:LINQ到SQL子查詢

public static IEnumerable<T> FilterCultureSubQuery<T>(this Table<T> t) 
    where T : class 
    { 
     return t; 
    } 

我試圖用它在此查詢

var test = from p in t.Products 
      select new 
      { 
       Allo = p, 
       Allo2 = (from pl in t.ProductLocales.FilterCultureSubQuery() 
         select pl) 
      }; 

什麼應該是我的方法的簽名延期?我總是得到這個錯誤:

 
Method 'System.Collections.Generic.IEnumerable`1[ProductLocale] FilterCultureSubQuery[ProductLocale](System.Data.Linq.Table`1[ProductLocale])' has no supported translation to SQL. 

我也試過這樣的簽名:

public static IQueryable<T> FilterCultureSubQuery<T>(this Table<T> t) 
    where T : class 
    { 
     return t; 
    } 

而且我得到了這個錯誤:

 
Method 'System.Linq.IQueryable`1[ProductLocale] FilterCultureSubQuery[ProductLocale](System.Data.Linq.Table`1[ProductLocale])' has no supported translation to SQL. 

感謝

回答

1

當我使用我的擴展方法在一個簡單的查詢,它的工作,但是當我在子查詢中使用它不工作。任何解決方案

工作

var test = from pl in t.ProductLocales.FilterCultureSubQuery() select pl; 

不工作

var test = from p in t.Products 
      select new 
      { 
      Allo = p, 
      Allo2 = (from pl in t.ProductLocales.FilterCultureSubQuery() 
         select pl) 
      }; 

我創建了一個新的擴展方法並重寫查詢表達式樹。

var test = (from p in t.Products 
       select new 
       { 
       Allo = p, 
       Allo2 = (from pl in t.ProductLocales.FilterCultureSubQuery() 
          select pl) 
       }).ArrangeExpression(); 

LINQ-TO-SQL難以在子查詢中使用擴展方法。用重寫表達式擴展方法everyting工作正常。

其他解決方案?

4

你的方法的簽名精細。如上所述,問題是「它沒有支持到SQL的轉換」。

DLINQ正在嘗試將該語句轉換爲它將發送到數據庫的SQL行。該方法沒有翻譯。

我建議使用Where子句重寫過濾器。

2

您的擴展方法沒有問題。

由於您試圖在LINQ-To-SQL查詢中使用您的自定義方法,並且LINQ-To-SQL不知道您的方法對SQL的轉換,您會得到該異常。所以它不能從你的LINQ表達式構造一個SQL查詢。

解決方案將首先獲取數據,然後應用您的轉換。