分页、排序、过滤分离

问题描述 投票:0回答:1

在我的 ASP.NET MVC 应用程序中,我有一个服务,该服务具有对车辆品牌进行分页、排序和过滤的方法:

     public class VehicleService : IVehicleService
 {
     private readonly DbContext _context;

     public VehicleService(DbContext context)
     {
         _context = context;
     }

       public async Task<IPagedList<VehicleMake>> GetVehicleMakesWithPaginationAsync(string search, int? page, string sort)
    {
        var makes = _context.VehicleMakes.AsQueryable();

        switch (sort)
        {
            case "Name desc":
                makes = makes.OrderByDescending(x => x.Name);
                break;
            default:
                makes = makes.OrderBy(x => x.Name);
                break;
        }

        return await makes.Where(x => x.Name.StartsWith(search) || search == null).ToPagedListAsync(page ?? 1, 5);
 }
}

在审查我的代码后,我被告知排序、过滤和分页应该位于具有接口的单独类中。我通过以下方式实现了:

排序:

internal class Sorting : ISorting
{
    private readonly DbContext _context;

    public Sorting(DbContext context)
    {
        _context = context;
    }

    public IEnumerable<VehicleMake> SortMakes(string sort)
    {
        var makes = _context.VehicleMakes.AsQueryable();

        makes = sort == "Name desc" ? makes.OrderByDescending(x => x.Name) : makes.OrderBy(x => x.Name);
        return makes;
    }
}

寻呼:

class Paging : IPaging
{
    private readonly ISorting _sorting;

    public Paging(DbContext context)
    {
        _sorting = new Sorting(context);
    }

    public async Task<IPagedList<VehicleMake>> GetPagedListOfSortedMakes(string search, int? page, string sort)
    {
        var sortedMakes = _sorting.SortMakes(sort).AsQueryable();
        return await sortedMakes.Where(x => x.Name.StartsWith(search) || search == null).ToPagedListAsync(page ?? 1, 5);
    }
}

然后为我服务:

    public class VehicleMakeService : IVehicleMakeService
{
    private readonly DbContext _context;
    private readonly IPaging _paging;

    public VehicleMakeService(DbContext context)
    {
        _context = context;
        _paging = new Paging(context);
    }

    public async Task<IPagedList<VehicleMake>> GetVehicleMakesWithPaginationAsync(string search, int? page, string sort)
    {
        return await _paging.GetPagedListOfSortedMakes(search, page, sort);
    }
}

这效果很好,但我不确定我是否正确实现了这一点。有没有更好(更干净)的方法来做到这一点?

c# asp.net-mvc sorting pagination filtering
1个回答
0
投票

您不使用的任何原因https://github.com/dncuug/X.PagedList

这似乎是一个非常好的组件。

© www.soinside.com 2019 - 2024. All rights reserved.