传递一个选择器功能时,排序依据是没有转化为SQL [英] OrderBy is not translated into SQL when passing a selector function
问题描述
当我执行:
var t = db.Table1.OrderBy(x => x.Name).ToList();
在SQL事件探查器,这是转换为SQL语句:
In SQL profiler, this is the translated SQL:
SELECT
[Extent1].[ID] AS [ID],
[Extent1].[Name] AS [Name]
FROM [dbo].[Table1] AS [Extent1]
ORDER BY [Extent1].[Name] ASC
这是正确的。
不过,如果我传递一个选择器功能来排序依据:
However, if I pass a selector function to OrderBy:
Func<Table1, string> f = x => x.Name;
var t = db.Table1.OrderBy(f).ToList();
转换为SQL语句是:
The translated SQL is:
SELECT
[Extent1].[ID] AS [ID],
[Extent1].[Name] AS [Name]
FROM [dbo].[Table1] AS [Extent1]
的排序依据是完全没有翻译。
The orderby is totally not translated.
这是什么问题?它们是相同的lambda函数,唯一的区别是在第二个情况下,首先分配给一个变量
What's the problem? They are the same lambda function, the only difference is in the 2nd case, it is first assigned to a variable.
推荐答案
原因在IQueryable的世界,你需要一个表达式来; Func键<的TModel,TValue>>
作为排序依据的扩展参数,而不是一个 Func键<的TModel,TValue> ;
Cause in a IQueryable world, you need an Expression<Func<TModel, TValue>>
as the OrderBy's extension parameter, not a Func<TModel, TValue>
的 http://msdn.microsoft.com/en-us/library/system.linq.queryable.orderby
这篇关于传递一个选择器功能时,排序依据是没有转化为SQL的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!