问题
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