Dynamic IQueryable order using string

Possible duplicate:
Dynamic LINQ OrderBy

I am trying to create a dynamic sort for an Iqueryable.
So you can see that I am following some examples that I see here in stackoverflow.

var query = dalSession.Query<T>(); var res = (from x in query orderby Extensions.Sort<T>(query, "FirstName") select x).Skip((paging.CurrentPageRecord)).Take(paging.PageSize); public static class Extensions { public static IQueryable<T> Sort<T>(this IQueryable<T> query, string sortField) { return query.OrderByDescending(s => s.GetType() .GetProperty(sortField)); } } 

This is the exception I get:

System.Linq.IQueryable 1[Partners.BusinessObjects.Affiliate] Sort[Affiliate](System.Linq.IQueryable 1 [Partners.BusinessObjects.Affiliate], System.String)

 Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code. Exception Details: System.NotSupportedException: System.Linq.IQueryable`1[Partners.BusinessObjects.Affiliate] Sort[Affiliate](System.Linq.IQueryable`1[Partners.BusinessObjects.Affiliate], System.String) 
+4
source share
2 answers

The problem is here: -

 s => s.GetType().GetProperty(sortField) 

When you try to access the IQueryable result set, it translates to SQL and the query runs against your database (rather than running in memory). The problem is that, obviously, your database does not know anything about your types, cannot call any methods on them and, of course, cannot reflect them.

You will need to create your own expression tree that can be translated into SQL. The API expression is quite complex and you will need to read a little if you really want to get it. Here's a good starting point when creating dynamic queries using an API expression for you .

Fortunately, your specific case is quite simple and there are examples of it here , here and here , but I really recommend you read a little to understand what is happening. If you just copy-paste, then you or someone else will have to support it and have a very sad time.

+2
source

Iain is right, your iqueryable begins to retrieve data only when it is really necessary. You can force load with a simple trick long dummy = query.Count () ;. This is not a complete solution, you want to avoid the complexity of building a query tree, so if the collection is not very large, just convert it to some sortable type.

-1
source

Source: https://habr.com/ru/post/1444362/


All Articles