2013-02-20 78 views
3

我剛開始交手,在編譯的LINQ查詢,以及所遇到的一些奇怪的行爲返回KeyValuePair。從一個LINQ編譯的查詢

該查詢編譯罰款:

public static Func<DataContext, string, object> GetJourneyByUrl = 
    CompiledQuery.Compile<DataContext, string, object>((DataContext dc, string urlSlug) => 
     from j in dc.Journeys 
     where !j.Deleted 
     where j.URLSlug.Equals(urlSlug) 
     select new KeyValuePair<string, int>(j.URLSlug, j.JourneyId) 
    ); 

但是,當我嘗試改變從對象的返回類型爲KeyValuePair像這樣:

public static Func<DataContext, string, KeyValuePair<string, int>> GetJourneyByUrl = 
    CompiledQuery.Compile<DataContext, string, KeyValuePair<string, int>>((DataContext dc, string urlSlug) => 
     from j in dc.Journeys 
     where !j.Deleted 
     where j.URLSlug.Equals(urlSlug) 
     select new KeyValuePair<string, int>(j.URLSlug, j.JourneyId) 
    ); 

我收到以下錯誤:

CS1662: Cannot convert lambda expression to delegate type 'System.Func<DataContext,string,System.Collections.Generic.KeyValuePair<string,int>>' because some of the return types in the block are not implicitly convertible to the delegate return type

如何從編譯後的查詢中返回一個KeyValuePair?或者我是以完全錯誤的方式進行討論的?

回答

6

已編譯的查詢將返回一組值,因此爲了使其工作,請嘗試將返回類型更改爲IEnumerable<KeyValuePair<string, int>> - 您將返回一組值,而不僅僅是一個值。然後,您可能想要將已編譯查詢的函數名稱更改爲GetJourneysByUrl

然後,要從結果集中獲取單個值(暗示函數名稱爲GetJourneyByUrl),則應添加一個函數以返回編譯查詢返回的第一個項目。

public static KeyValuePair<string, int> GetJourneyByUrl(DataContext dc, string urlSlug) { 
    return GetJourneysByUrl(dc, urlSlug).First(); 
} 

您也可以設置此爲Func,在此msdn page related to compiled queries,如圖所示。

+0

然後使用。首先()或。單(或類似的方法),以獲得您需要 – ry8806 2013-02-20 11:41:22

+0

點值!而不是創建另一個包裝方法,我在()中包裝了我的初始查詢(在我的Func中),然後使用first或default。謝謝! – seanxe 2013-02-20 11:51:47