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?
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.
Polymorphic element types in collectionsAutoMapper supports polymorphic arrays and collections, such that derived source/destination types are used if found.
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.
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.
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>();
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:
Write a custom IObjectMapper
, using the existing Array/EnumerableMappers as a guide. This is the way I would go personally.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With