OrderBy is not translated into SQL when passing a selector function

邮差的信 提交于 2019-12-02 01:36:20

问题


When I execute:

var t = db.Table1.OrderBy(x => x.Name).ToList();

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

Which is correct.

However, if I pass a selector function to OrderBy:

Func<Table1, string> f = x => x.Name;
var t = db.Table1.OrderBy(f).ToList();

The translated SQL is:

SELECT 
[Extent1].[ID] AS [ID], 
[Extent1].[Name] AS [Name]
FROM [dbo].[Table1] AS [Extent1]

The orderby is totally not translated.

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.


回答1:


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



来源:https://stackoverflow.com/questions/12210799/orderby-is-not-translated-into-sql-when-passing-a-selector-function

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!