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
I needed to return a serializable version of IPagedList<> with AutoMapper version 6.0.2 that supports the IMapper interface for ASP.NET Web API. So, if the question was how do I support the following:
//Mapping from an enumerable of "foo" to a different enumerable of "bar"...
var listViewModel = _mappingEngine.Map, PagedViewModel>(requestForQuotes);
Then one could do this:
Define PagedViewModel
Source: AutoMapper Custom Type Converter not working
public class PagedViewModel
{
public int FirstItemOnPage { get; set; }
public bool HasNextPage { get; set; }
public bool HasPreviousPage { get; set; }
public bool IsFirstPage { get; set; }
public bool IsLastPage { get; set; }
public int LastItemOnPage { get; set; }
public int PageCount { get; set; }
public int PageNumber { get; set; }
public int PageSize { get; set; }
public int TotalItemCount { get; set; }
public IEnumerable Subset { get; set; }
}
Write open generic converter from IPagedList to PagedViewModel
Source: https://github.com/AutoMapper/AutoMapper/wiki/Open-Generics
public class Converter : ITypeConverter, PagedViewModel>
{
public PagedViewModel Convert(IPagedList source, PagedViewModel destination, ResolutionContext context)
{
return new PagedViewModel()
{
FirstItemOnPage = source.FirstItemOnPage,
HasNextPage = source.HasNextPage,
HasPreviousPage = source.HasPreviousPage,
IsFirstPage = source.IsFirstPage,
IsLastPage = source.IsLastPage,
LastItemOnPage = source.LastItemOnPage,
PageCount = source.PageCount,
PageNumber = source.PageNumber,
PageSize = source.PageSize,
TotalItemCount = source.TotalItemCount,
Subset = context.Mapper.Map, IEnumerable>(source) //User mapper to go from "foo" to "bar"
};
}
}
Configure mapper
new MapperConfiguration(cfg =>
{
cfg.CreateMap();//Define each object you need to map
cfg.CreateMap(typeof(IPagedList<>), typeof(PagedViewModel<>)).ConvertUsing(typeof(Converter<,>)); //Define open generic mapping
});