2013-10-17 26 views
0

我已經在我的一個問題中給出了這個解決方案......看起來很有趣..因爲我正在嘗試和學習理解LINQ ..我在執行這個時遇到了這個錯誤。我不知道這裏出了什麼問題......尋求專家意見。IEqualityComparer上的錯誤<T>

public class CategotiesEqualityComparer : IEqualityComparer<ac_Categories> 
{ 
    public bool Equals(ac_Categories x, ac_Categories y) 
    { 
     return x.ThumbnailAltText.Trim() == y.ThumbnailAltText.Trim(); 
    } 

    public int GetHashCode(ac_Categories obj) 
    { 
     return obj.ThumbnailAltText.Trim().GetHashCode(); 
    } 
} 

var catlist = _db.ac_Categories 
.Where(c => c.VisibilityId == 0 && c.ThumbnailAltText != null 
    && (!c.ThumbnailAltText.StartsWith("gifts/") 
    && !c.ThumbnailAltText.StartsWith("email/") 
    && !c.ThumbnailAltText.StartsWith("news/") 
    && !c.ThumbnailAltText.StartsWith("promotions/") 
    && !c.ThumbnailAltText.StartsWith("the-knowledge/"))) 
    .Distinct(new CategotiesEqualityComparer()).ToList(); 

ERROR:LINQ to Entities does not recognize the method 'System.Linq.IQueryable 1[WebMgr.ac_Categories] Distinct[ac_Categories](System.Linq.IQueryable 1[WebMgr.ac_Categories], System.Collections.Generic.IEqualityComparer`1[WebMgr.ac_Categories])' method, and this method cannot be translated into a store expression

注:

我使用數據庫第一種方法和ac_Categories使用創建...

+3

您的問題已經在這裏解答:http://stackoverflow.com/a/1011014/222163 –

回答

4

你不可錯過的IEqualityComparer比較器爲呼叫到EF查詢或者可能是大多數IQueryable集合。 IQueryable是表達式樹,表達式樹被轉換爲底層查詢(例如帶EF的SQL)。因此它不能在SQL中執行你的代碼。

正常的Distinct()調用將工作得很好,如果你想過濾掉重複的相同記錄,因爲它會執行一個獨特的SQL。如果你要應用你的相等比較器,你將不得不將數據拉入內存然後應用你的截然不同。

+1

是的......我明白了....我必須使用AsEnumerable() –

+2

是的,但請注意,這將會只有在SQL中執行WHERE時,纔會在內存中執行不同的操作。取決於數據集的大小,group by可能更快。 –

相關問題