OrderBy is not translated into SQL when passing a selector function
Asked Answered
F

1

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.

Feckless answered 31/8, 2012 at 7:32 Comment(0)
H
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

Hasa answered 31/8, 2012 at 11:11 Comment(4)
Thanks. Wrapping the function with an expression solved the problem. But why there is no compile error when I pass a function to OrderBy?Feckless
Also, I know I can wrap a function with an expression like: Expression<Func<Table1, string>> f = x => x.Name; But if I aleady have the function variable, how can I convert it to an Expression? ThanksFeckless
@NanLi no compile error, because IQueryable inherits from IEnumerable, which have an OrderBy method with an Func<TModel, TValue> parameter. For the second question, see this : #768233Filament
@NanLi I'm also curious : #12222506Filament

© 2022 - 2024 — McMap. All rights reserved.