Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can Automapper map a paged list?

Tags:

I'd like to map a paged list of business objects to a paged list of view model objects using something like this:

var listViewModel = _mappingEngine.Map<IPagedList<RequestForQuote>, IPagedList<RequestForQuoteViewModel>>(requestForQuotes); 

The paged list implementation is similar to Rob Conery's implementation here: http://blog.wekeroad.com/2007/12/10/aspnet-mvc-pagedlistt/

How can you setup Automapper to do this?

like image 616
ChrisR Avatar asked Jan 15 '10 10:01

ChrisR


People also ask

How do I use AutoMapper to list a map?

Once you have your types, and a reference to AutoMapper, you can create a map for the two types. Mapper. CreateMap<Order, OrderDto>(); The type on the left is the source type, and the type on the right is the destination type.

Can AutoMapper map collections?

Polymorphic element types in collectionsAutoMapper supports polymorphic arrays and collections, such that derived source/destination types are used if found.

Is AutoMapper faster than manual mapping?

Inside this article, it discusses performance and it indicates that Automapper is 7 times slower than manual mapping. This test was done on 100,000 records and I must say I was shocked.

What is AutoMapper good for?

AutoMapper is a simple library that helps us to transform one object type into another. It is a convention-based object-to-object mapper that requires very little configuration. The object-to-object mapping works by transforming an input object of one type into an output object of a different type.


2 Answers

Using jrummell's answer, I created an extension method that works with Troy Goode's PagedList. It keeps you from having to put so much code everywhere...

    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;      } 

Usage is:

var pagedDepartments = database.Departments.OrderBy(orderBy).ToPagedList(pageNumber, pageSize).ToMappedPagedList<Department, DepartmentViewModel>(); 
like image 180
Brian McCord Avatar answered Sep 21 '22 19:09

Brian McCord


AutoMapper does not support this out of the box, as it doesn't know about any implementation of IPagedList<>. You do however have a couple of options:

  1. Write a custom IObjectMapper, using the existing Array/EnumerableMappers as a guide. This is the way I would go personally.

  2. Write a custom TypeConverter, using:

    Mapper     .CreateMap<IPagedList<Foo>, IPagedList<Bar>>()     .ConvertUsing<MyCustomTypeConverter>(); 

    and inside use Mapper.Map to map each element of the list.

like image 24
Jimmy Bogard Avatar answered Sep 20 '22 19:09

Jimmy Bogard