示例#1
0
        public async Task <IActionResult> GetEvents(
            [FromQuery] PaginationFilter filter, [FromQuery] string sortBy, [FromQuery] string search, [FromQuery] string order = "asc")
        {
            sortBy = string.IsNullOrEmpty(sortBy) ? "Id" : sortBy;
            var sortByProperty = typeof(Event).GetProperty(sortBy);

            var resultList = new List <Event>();

            if (search != null)
            {
                await foreach (var currentEvent in _context.Events)
                {
                    if (currentEvent.ToString().Contains(search))
                    {
                        resultList.Add(currentEvent);
                    }
                }
            }
            else
            {
                resultList = _context.Events.ToList();
            }

            var pageFilter = new PaginationFilter(filter.PageNumber, filter.PageSize);

            var pagedData = resultList
                            .Skip((pageFilter.PageNumber - 1) * pageFilter.PageSize)
                            .Take(pageFilter.PageSize).ToList().OrderBy(employee =>
                                                                        sortByProperty?.GetValue(employee)).ToList();

            if (order == "desc")
            {
                pagedData.Reverse();
            }

            var totalRecords = await _context.Events.CountAsync();

            var pagedResponse = Pagination.CreatePagedResponse(pagedData, pageFilter, totalRecords);

            if (pagedResponse.TotalRecords == 0)
            {
                pagedResponse.Message = "Page is empty";
            }
            return(Ok(pagedResponse));
        }