在我的ASP.NET MVC应用程序中,我有一个服务,它有一个分页,排序和过滤Vehicle Makes的方法:
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);
}
}
这很有效,但我不确定我是否正确实现了这一点。是否有更好(更清洁)的方法来做到这一点?