Quantcast
Channel: URF - Unit of Work & (extensible/generic) Repositories Framework
Viewing all articles
Browse latest Browse all 1539

New Post: Add Sort Extension by Column name

$
0
0
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:
   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);

Viewing all articles
Browse latest Browse all 1539

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>