Automapper可以映射分页列表吗?

Chr*_*isR 19 c# automapper

我想使用以下内容将页面的业务对象列表映射到视图模型对象的分页列表:

var listViewModel = _mappingEngine.Map<IPagedList<RequestForQuote>, IPagedList<RequestForQuoteViewModel>>(requestForQuotes);
Run Code Online (Sandbox Code Playgroud)

分页列表实现类似于Rob Conery在此处的实现:http: //blog.wekeroad.com/2007/12/10/aspnet-mvc-pagedlistt/

如何设置Automapper来执行此操作?

Bri*_*ord 33

使用jrummell的答案,我创建了一个与Troy Goode的PagedList一起使用的扩展方法.它让你不必在任何地方放置如此多的代码......

    public static IPagedList<TDestination> ToMappedPagedList<TSource, TDestination>(this IPagedList<TSource> list)
    {
        IEnumerable<TDestination> sourceList = Mapper.Map<IEnumerable<TSource>, IEnumerable<TDestination>>(list);
        IPagedList<TDestination> pagedResult = new StaticPagedList<TDestination>(sourceList, list.GetMetaData());
        return pagedResult;

    }
Run Code Online (Sandbox Code Playgroud)

用法是:

var pagedDepartments = database.Departments.OrderBy(orderBy).ToPagedList(pageNumber, pageSize).ToMappedPagedList<Department, DepartmentViewModel>();
Run Code Online (Sandbox Code Playgroud)

  • 这完全是我想要的**.它也有效.谢谢. (3认同)

Jim*_*ard 12

AutoMapper不支持这种开箱即用,因为它不知道任何实现IPagedList<>.但是你有两个选择:

  1. IObjectMapper使用现有的Array/EnumerableMappers作为指南编写自定义.这是我亲自去的方式.

  2. 编写自定义TypeConverter,使用:

    Mapper
        .CreateMap<IPagedList<Foo>, IPagedList<Bar>>()
        .ConvertUsing<MyCustomTypeConverter>();
    
    Run Code Online (Sandbox Code Playgroud)

    和内部用于Mapper.Map映射列表的每个元素.

  • 可以在此处找到将Troy Goode的PagedList工作的TypeConverter转换为简单的ViewModel:http://stackoverflow.com/questions/12470156/automapper-custom-type-converter-not-working/12538611#12538611 (2认同)

jru*_*ell 7

如果你正在使用Troy Goode的PageList,那么有一个StaticPagedList类可以帮助你进行映射.

// get your original paged list
IPagedList<Foo> pagedFoos = _repository.GetFoos(pageNumber, pageSize);
// map to IEnumerable
IEnumerable<Bar> bars = Mapper.Map<IEnumerable<Bar>>(pagedFoos);
// create an instance of StaticPagedList with the mapped IEnumerable and original IPagedList metadata
IPagedList<Bar> pagedBars = new StaticPagedList<Bar>(bars, pagedFoos.GetMetaData());
Run Code Online (Sandbox Code Playgroud)