public static SortingInfo Parse(string sortingHeader)
        {
            if (sortingHeader == null)
            {
                return(null);
            }

            var sorting = new SortingInfo();

            var keys = sortingHeader.Split(';');

            foreach (var key in keys)
            {
                if (!key.EndsWith("_asc") && !key.EndsWith("_dsc"))
                {
                    throw new InvalidOperationException("Sorting Header mal formed for sorting");
                }

                var values    = key.Split('_');
                var direction = values[1].ToLower().Equals("asc") ? Sorting.Asc : Sorting.Dsc;
                var orderBy   = values[0];
                sorting.Add(orderBy, direction);
            }

            return(sorting);
        }
예제 #2
0
 public override void OnActionExecuting(ActionExecutingContext context)
 {
     if (context.ActionArguments.Values.OfType <SortingInfo>().Any())
     {
         var sortingInfo = context.ActionArguments.Values.OfType <SortingInfo>().First();
         if (context.HttpContext.Request.Query.ContainsKey("sort"))
         {
             var items = SortingInfo.Parse(context.HttpContext.Request.Query["sort"]);
             foreach (var item in items.Iterator())
             {
                 sortingInfo.Add(item);
             }
         }
     }
 }
        public static IOrderedQueryable <T> IncludeOrderBy <T>(this IQueryable <T> query, SortingInfo sortingInfo)
        {
            IOrderedQueryable <T> orderedQueryable = null;

            foreach (var sortingElement in sortingInfo.Iterator())
            {
                var orderBy = sortingElement.GetOrderBy();

                var param        = orderBy;
                var propertyInfo = typeof(T).GetProperty(param);
                if (orderedQueryable == null)
                {
                    orderedQueryable = sortingElement.IsAsc()
                        ? query.OrderBy(x => propertyInfo.GetValue(x, null))
                        : query.OrderByDescending(x => propertyInfo.GetValue(x, null));
                }
                else
                {
                    orderedQueryable = sortingElement.IsAsc()
                        ? orderedQueryable.ThenBy(x => propertyInfo.GetValue(x, null))
                        : orderedQueryable.ThenByDescending(x => propertyInfo.GetValue(x, null));
                }
            }
            return(orderedQueryable);
        }