2010-10-19 31 views
0

在Linq查詢中使用自定義比較器有什麼用處?它們是有益的還是它們只是服務器上的重載?在dB上使用自定義比較器的Linq查詢

,所以我講的查詢,如

IEnumerable<Class> GetMatch(Class comparerObject) 
{ 
    return Session.Linq<Class>().Where(x=>new StringComparer<Class>().Equals(x,comparerObject)) 
} 

,這是我stringcomparer類看起來像

public class StringComparer<T> : IEqualityComparer<T> 
    where T : class, IStringIdentifiable 
{ 
    public bool Equals(T x, T y) 
    { 
     if (x == null && y == null) 
      return true; 

     if (x == null || y == null) 
      return false; 

     return x.Id.Equals(y.Id, StringComparison.OrdinalIgnoreCase); 
    } 

所以我想知道這是怎麼查詢對數據庫運行?我認爲linq在內部處理它,只有在comparere中的所有情況都運行後,它纔會向db發送請求。

編輯:

那麼,如果你發現很難相信,上面不會有工作,然後拿一個簡單的例子,像

return Session.Linq<Class>().Where(x=>x.Id.Equals(comparerObject,StringComparison.InvariantCultureIgnoreCase)) 

那麼你覺得什麼是預期的行爲?

謝謝。

回答

1

對於LINQ to SQL,我期望在執行時失敗 - 查詢翻譯器將不知道如何處理您的類StringComparer<T>

在你給的情況下,你應該只使用:根據正是你想達到什麼

string idToMatch = comparerObject.Id; 
return Session.Linq<Class>().Where(x => x.Id == idToMatch); 

更復雜的情況下,可能會或可能不會是可行的。

+0

我的印象是,如果Linq不知道如何將給定的代碼翻譯成SQL,它只會拉出所有沒有這種條件的數據,並將它應用到內存集合中,而不是在執行失敗時間?或者我在想一些不相干的東西? – R0MANARMY 2010-10-19 16:00:03

+0

@ R0MANARMY:如果你想通過調用AsEnumerable來做到這一點,但默認情況下它不會這樣做。 – 2010-10-19 16:51:07

+0

謝謝你澄清,必須記住IQueryable不喜歡它不能翻譯的東西。 – R0MANARMY 2010-10-19 16:57:46