由于c#有强大的linq特性以及支持方法扩展,我们不需要什么第三方插件就能自己实现分页功能

  1. 为了程序的可扩展性,分页参数可能会发生变化,不妨将分页参数如下封装起来在Asp .net core 中不依赖插件实现分页_可扩展性

    public class PaginationResourceParameters
        {
            private const int MAXPAGESIZE = 50;
            private int _pageNumber = 1;
            public int PageNumber
            {
                get
                { return _pageNumber; }
                set
                {
                    if (value >= 1)
                    {
                        _pageNumber = value;
                    }
                }
            }
            private int _pageSize = 10;
            public int PageSize
            {
                get
                { return _pageSize; }
                set
                {
                    if (value >= 1)
                    {
                        _pageSize = (value > MAXPAGESIZE) ? MAXPAGESIZE : value;
                    }
                }
            }
        }
    
  2. 在控制器的Action中传入分页参数在Asp .net core 中不依赖插件实现分页_第三方插件_02

  3. 调用repository时传入分页参数

  4. 创建一个分页helper在Asp .net core 中不依赖插件实现分页_分页_03

    public class PaginationList<T> : List<T>
        {
            public int TotalPages { get; private set; }
            public int TotalCount { get; private set; }
            public int CurrentPage { get; set; }
            public bool HasPrevious => CurrentPage > 1;
            public bool HasNext => CurrentPage < TotalPages;
            public int PageSize { get; set; }
    
            public PaginationList(int totalcount, int currentPage, int pageSize, List<T> items)
            {
                CurrentPage = currentPage;
                PageSize = pageSize;
                TotalCount = totalcount;
                TotalPages = (int)Math.Ceiling(totalcount / (double)pageSize);
                AddRange(items);
            }
    
            public static async Task<PaginationList<T>> CreateAsync(
                int currentPage, int pageSize, IQueryable<T> result)
            {
                var totalCount = await result.CountAsync();
                var skip = (currentPage - 1) * pageSize;
                result = result.Skip(skip);
                result = result.Take(pageSize);
    
                var items = await result.ToListAsync();
    
                return new PaginationList<T>(totalCount, currentPage, pageSize, items);
            }
        }
    
  5. 在repository中调用PaginationList实现分页

    return await PaginationList<TouristRoute>.CreateAsync(pageNumber, pageSize, res);