我的数据库中有9个项目,但是在地图项目之后,项目的总数是pageSize,并且页面总是显示一页。
public async Task<ActionResult> Index(int? page)
{
int pageSize = 3;
int pageNumber = (page ?? 1);
var result = db.Projects.OrderByDescending(x => x.StartDate);
var model = result.ToPagedList(pageNumber, pageSize);
var model2 = AutoMapper.Mapper.Map<PagedList<ProjectViewModel>>(model);
return View(model2);
}
public class PagedListConverter : ITypeConverter<PagedList<Project>, PagedList<ProjectViewModel>>
{
public PagedList<ProjectViewModel> Convert(ResolutionContext context)
{
var model = (PagedList<Project>)context.SourceValue;
var vm = model.Select(m => Mapper.Map<Project, ProjectViewModel>(m)).ToList();
return new PagedList<ProjectViewModel>(vm, model.PageNumber, model.PageSize);
}
}
在我的automapper配置中,我写下了这个
AutoMapper.Mapper.CreateMap<Project, ProjectViewModel>();
Mapper.CreateMap<PagedList<Project>, PagedList<ProjectViewModel>>().ConvertUsing<PagedListConverter>();
答案 0 :(得分:0)
如果您需要将AutoMapper
与PagedList
结合使用,则必须使用StaticPagedList
手动创建分页列表。这意味着您需要手动限制查询集并自己获取总计数。例如:
int pageSize = 3;
int pageNumber = (page ?? 1);
var result = db.Projects.OrderByDescending(x => x.StartDate).Skip(pageSize * (pageNumber - 1)).Take(pageSize);
var totalResults = db.Projects.Count();
var model = AutoMapper.Mapper.Map<List<ProjectViewModel>>(result);
var model2 = new StaticPagedList<ProjectViewModel>(model, pageNumber, pageSize, totalResults);
return View(model2);
这意味着要进行两次查询(一次是为页面选择项目而另一次是为了获得总计数),但计数查询相对较快。无论如何,这是通过AutoMapper
进行分页和映射到另一个类类型的唯一方法。