传递选择器函数时,OrderBy不会转换为SQL

时间:2012-08-31 07:32:28

标签: c# entity-framework linq-to-entities sql-order-by sqlprofiler

执行时:

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

在SQL事件探查器中,这是已翻译的SQL:

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

哪个是正确的。

但是,如果我将选择器函数传递给OrderBy:

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

翻译的SQL是:

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

orderby完全没有翻译。

有什么问题?它们是相同的lambda函数,唯一的区别在于第二种情况,它首先被赋值给一个变量。

1 个答案:

答案 0 :(得分:3)

因为在IQueryable世界中,您需要Expression<Func<TModel, TValue>>作为OrderBy的扩展参数,而不是Func<TModel, TValue>

http://msdn.microsoft.com/en-us/library/system.linq.queryable.orderby