简体   繁体   中英

Returning KeyValuePair from a Linq Compiled Query

I'm just getting to grips with Compiled Queries in Linq, and have come across some strange behaviour.

This query compiles fine:

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)
    );

But when I try and change the return type from object to a KeyValuePair like so:

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)
    );

I get the following error:

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

How can I return a single KeyValuePair from a compiled query? Or am I going about this completely the wrong way?

The compiled query will return a set of values, so in order to get it working, try changing the return type to IEnumerable<KeyValuePair<string, int>> - you are returning a set of values, not just one single value. You might then want to change the function name for the compiled query to GetJourneysByUrl .

Then to get a single value from the result set (implied by the function name of GetJourneyByUrl ) then you should add a function to return the first item returned by the compiled query.

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

You can also set this up as a Func , as shown on this msdn page related to compiled queries .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM