我刚刚接触到Linq中的Compiled Queries,并且遇到了一些奇怪的行为 .
此查询编译正常:
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:无法将lambda表达式转换为委托类型'System.Func <DataContext,string,System.Collections.Generic.KeyValuePair <string,int >>',因为块中的某些返回类型不能隐式转换为委托返回类型
如何从编译的查询中返回单个 KeyValuePair
?或者我完全以错误的方式解决这个问题?
1 回答
编译后的查询将返回一组值,因此为了使其正常工作,请尝试将返回类型更改为
IEnumerable<KeyValuePair<string, int>>
- 您将返回一组值,而不仅仅是一个值 . 然后,您可能希望将已编译查询的函数名称更改为GetJourneysByUrl
.然后,要从结果集中获取单个值(由
GetJourneyByUrl
的函数名称隐含),那么您应该添加一个函数来返回编译查询返回的第一个项目 .您也可以将其设置为
Func
,如msdn page related to compiled queries所示 .