当我执行时:
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 函数,唯一的区别是在第二种情况下,它首先分配给一个变量。