Result - Build a custom IObjectMapper to do the mapping
Resulting Action
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
[AutoMap(typeof(EventListViewModel))] | |
public ActionResult Index(int? page) | |
{ | |
page = page ?? 1; | |
var entities = //load data from database | |
.AsPagination(page.Value, 20); //pagination method from MVC Contrib | |
return View(entities); | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class PaginationMapper : IObjectMapper | |
{ | |
private IMappingEngineRunner _mapper; | |
public T Map<T>(object source) | |
{ | |
TypeMap typeMap = _mapper.ConfigurationProvider.FindTypeMapFor(source, source.GetType(), typeof(T)); | |
MappingOperationOptions mappingOperationOptions = new MappingOperationOptions(); | |
ResolutionContext resolutionContext = new ResolutionContext(typeMap, source, source.GetType(), typeof(T), mappingOperationOptions); | |
return (T)_mapper.Map(resolutionContext); | |
} | |
public PagedList<T> CreatePagedList<T>(IPagination source) | |
{ | |
var result = Activator.CreateInstance<PagedList<T>>(); | |
result.TotalItems = source.TotalItems; | |
result.TotalPages = source.TotalPages; | |
result.HasNextPage = source.HasNextPage; | |
result.HasPreviousPage = source.HasPreviousPage; | |
result.PageNumber = source.PageNumber; | |
result.PageSize = source.PageSize; | |
result.FirstItem = source.FirstItem; | |
result.LastItem = source.LastItem; | |
foreach (var item in source) | |
{ | |
result.Add(Map<T>(item)); | |
} | |
return result; | |
} | |
public object Map(ResolutionContext context, IMappingEngineRunner mapper) | |
{ | |
_mapper = mapper; | |
Type destinationType = context.DestinationType.GetGenericArguments()[0]; | |
var method = typeof(PaginationMapper).GetMethod("CreatePagedList").MakeGenericMethod(destinationType); | |
return method.Invoke(this, new[] { context.SourceValue }); | |
} | |
public bool IsMatch(ResolutionContext context) | |
{ | |
return typeof(IPagination).IsAssignableFrom(context.SourceType) && typeof(IPagination).IsAssignableFrom(context.DestinationType); | |
} | |
} |