Ejemplo n.º 1
0
        /// <summary>
        /// Applies data processing (paging, sorting, filtering and aggregates) over IQueryable using Dynamic Linq.
        /// </summary>
        /// <typeparam name="T">The type of the IQueryable.</typeparam>
        /// <param name="queryable">The IQueryable which should be processed.</param>
        /// <param name="take">Specifies how many items to take. Configurable via the pageSize setting of the Kendo DataSource.</param>
        /// <param name="skip">Specifies how many items to skip.</param>
        /// <param name="sort">Specifies the current sort order.</param>
        /// <param name="filter">Specifies the current filter.</param>
        /// <param name="aggregates">Specifies the current aggregates.</param>
        /// <param name="group">Specifies the current groups.</param>
        /// <returns>A DataSourceResult object populated from the processed IQueryable.</returns>
        public static DataSourceResult ToDataSourceResult <T>(this IQueryable <T> queryable, int take, int skip, IEnumerable <Sort> sort, Filter filter, IEnumerable <Aggregator> aggregates, IEnumerable <Group> group)
        {
            var errors = new List <object>();

            // Filter the data first
            queryable = Filter(queryable, filter, errors);

            // Calculate the total number of records (needed for paging)
            var total = queryable.Count();

            // Calculate the aggregates
            var aggregate = Aggregate(queryable, aggregates);

            if (group != null && group.Any())
            {
                //if(sort == null) sort = GetDefaultSort(queryable.ElementType, sort);
                if (sort == null)
                {
                    sort = new List <Sort>();
                }

                foreach (var source in group.Reverse())
                {
                    sort = sort.Append(new Sort
                    {
                        Field = source.Field,
                        Dir   = source.Dir
                    });
                }
            }

            // Sort the data
            queryable = Sort(queryable, sort);

            // Finally page the data
            if (take > 0)
            {
                queryable = Page(queryable, take, skip);
            }

            var result = new DataSourceResult
            {
                Total      = total,
                Aggregates = aggregate
            };

            // Group By
            if ((group != null) && group.Any())
            {
                var groupedQuery = queryable.ToList().GroupByMany(group);
                result.Group = groupedQuery;
            }
            else
            {
                result.Data = queryable.ToList();
            }

            // Set errors if any
            if (errors.Any())
            {
                result.Errors = errors;
            }

            return(result);
        }