namespace Routine.Api.ResourceParameters
{
public class CompanyDtoParameter
{
private const int MaxPageSize = 20;
public string CompanyName { get; set; }
public string SearchTerm { get; set; }
public int PageNumber { get; set; } = 1;
private int pageSize = 5;
public int PageSize
{
get => pageSize;
set => pageSize = (value > MaxPageSize) ? MaxPageSize : value;
}
}
}
PagedList类定义
ResourceUriType:
namespace Routine.Api.Helpers
{
public enum ResourceUriType
{
PreviousePage,
NextPage
}
}
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace Routine.Api.Helpers
{
public class PagedList<T> : List<T>
{
public int CurrentPage { get; set; }
public int TotalPages { get; set; }
public int PageSize { get; set; }
public int TotalCount { get; set; }
public bool HasPrevious => CurrentPage > 1;
public bool HasNext => CurrentPage < TotalPages;
public PagedList(List<T> items, int count, int pageNumber, int pageSize)
{
TotalCount = count;
PageSize = pageSize;
CurrentPage = pageNumber;
TotalPages = (int)Math.Ceiling(count / (double)PageSize);
AddRange(items);
}
public static async Task<PagedList<T>> CreateAsync(IQueryable<T> source, int pageNumber, int pageSize)
{
var count = await source.CountAsync();
var items = await source.Skip((pageNumber - 1) * pageSize).Take(pageSize).ToListAsync();
return new PagedList<T>(items, count, pageNumber, pageSize);
}
}
}
查询定义:
public async Task<PagedList<Company>> GetCompaniesAsync(CompanyDtoParameter parameter)
{
if (parameter == null)
{
throw new ArgumentNullException(nameof(parameter));
}
var queryExpression = context.Companies as IQueryable<Company>;
if (!string.IsNullOrWhiteSpace(parameter.CompanyName))
{
queryExpression = queryExpression.Where(x => x.Name == parameter.CompanyName.Trim());
}
if (!string.IsNullOrWhiteSpace(parameter.SearchTerm))
{
queryExpression = queryExpression.Where(x => x.Name == parameter.SearchTerm.Trim() ||
x.Introduction.Contains(parameter.SearchTerm.Trim()));
}
//分页
//queryExpression = queryExpression
// .Skip(parameter.PageSize * (parameter.PageNumber - 1))
// .Take(parameter.PageSize);
//return await queryExpression.ToListAsync();
return await PagedList<Company>.CreateAsync(queryExpression, parameter.PageNumber, parameter.PageSize);
}
请发表评论