I try to make the sort by Column Name and direction by Boolean, because this is send from client with Grid. I don't know about another available function in EF6 or something else. Please show me if there is better code for that.
But I test this and it work, except I don't check when column is empty. This must be check in your BLL with a default column sort.
Just add this class into Repository.Pattern.Ef6, I think that place is suite:
But I test this and it work, except I don't check when column is empty. This must be check in your BLL with a default column sort.
Just add this class into Repository.Pattern.Ef6, I think that place is suite:
public static class OrderHelper
{
private static IOrderedQueryable<T> OrderingHelper<T>(IQueryable<T> source, string propertyName, bool descending, bool anotherLevel)
{
ParameterExpression param = Expression.Parameter(typeof(T), string.Empty); // I don't care about some naming
MemberExpression property = Expression.PropertyOrField(param, propertyName);
LambdaExpression sort = Expression.Lambda(property, param);
MethodCallExpression call = Expression.Call(
typeof(Queryable),
(!anotherLevel ? "OrderBy" : "ThenBy") + (descending ? "Descending" : string.Empty),
new[] { typeof(T), property.Type },
source.Expression,
Expression.Quote(sort));
return (IOrderedQueryable<T>)source.Provider.CreateQuery<T>(call);
}
public static IOrderedQueryable<T> OrderBy<T>(this IQueryable<T> source, string propertyName, bool descending = false)
{
return OrderingHelper(source, propertyName, descending, false);
}
public static IOrderedQueryable<T> ThenBy<T>(this IOrderedQueryable<T> source, string propertyName, bool descending = false)
{
return OrderingHelper(source, propertyName, descending, true);
}
}
And use in Services like example below that:string orderBy = "Column1"; boolean descending = false;
base.Query().OrderBy(q => q.OrderBy(orderBy, descending))
.SelectPage(page, pageSize, out totalCount);