2

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.

abatishchev
  • 98,240
  • 88
  • 296
  • 433
Nan Li
  • 603
  • 1
  • 7
  • 18

1 Answers1

3

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

Raphaël Althaus
  • 59,727
  • 6
  • 96
  • 122
  • 1
    Thanks. Wrapping the function with an expression solved the problem. But why there is no compile error when I pass a function to OrderBy? – Nan Li Aug 31 '12 at 16:17
  • Also, I know I can wrap a function with an expression like: Expression> f = x => x.Name; But if I aleady have the function variable, how can I convert it to an Expression? Thanks – Nan Li Aug 31 '12 at 16:22
  • @NanLi no compile error, because IQueryable inherits from IEnumerable, which have an OrderBy method with an `Func` parameter. For the second question, see this : http://stackoverflow.com/questions/767733/converting-a-net-funct-to-a-net-expressionfunct – Raphaël Althaus Aug 31 '12 at 20:09
  • @NanLi I'm also curious : http://stackoverflow.com/questions/12222006/iqueryable-orderby-with-functmodel-tvalue-whats-happening – Raphaël Althaus Aug 31 '12 at 20:23