public static IQueryable<TResult> ApplySortFilter<T, TResult>(this IQueryable<T> query, string columnName)
where T : EntityObject
{
var param = Expression.Parameter(typeof(T), "o");
var body = Expression.PropertyOrField(param,columnName);
var sortExpression = Expression.Lambda(body, param);
return query.OrderBy(sortExpression);
}
Because the type for OrderBy is not inferred from sortExpression I need to specify it something like this at run time:
var sortExpression = Expression.Lambda<T, TSortColumn>(body, param);
Or
return query.OrderBy<T, TSortColumn>(sortExpression);
I don't think this is possible however as TSortColumn can only be determined during runtime.
Is there a way around this?
I used your idea for extension method for OrderBy. But in case of "many to many" I am getting error. For example you have table Site, Customer and Customer_site. For given Site I want to sort by customer name and in OrderBy extension (when I pass "site.customer" where customer is navigation property) I get error in line: propertyAccess = Expression.MakeMemberAccess(propertyAccess, property);
This is what I use (with some enhancements :-) ):
Regards
Slobodan
I've extended your functions to add support for Child Properties.
You can use these functions like:
I fixed this code a bit: https://stackoverflow.com/a/1670085/5852630
This code works with sequential sorting: first execute "OrderBy", then "ThenBy"(Not "OrderBy"!)
Here is my adaptation from @Davy Landman's answer (I wanted an extension method) and I simplified a bit.
It can be used like this:
It seems that this is the way to do it, now to verify that:
We did something similar (not 100% the same, but similar) in a LINQ to SQL project. Here's the code:
We didn't actually use a generic, we had a known class, but it should work on a generic (I've put the generic placeholder where it should be).
Edit: For descending order, pass in
OrderByDescending
instead of "OrderBy":