我需要返回IPagedList<>
與AutoMapper版本6.0.2序列化的版本,支持IMapper
ASP.NET Web API的接口。因此,如果這個問題是我怎麼支持以下內容:
//Mapping from an enumerable of "foo" to a different enumerable of "bar"...
var listViewModel = _mappingEngine.Map<IPagedList<RequestForQuote>, PagedViewModel<RequestForQuoteViewModel>>(requestForQuotes);
那麼可以這樣做:
定義PagedViewModel<T>
來源:AutoMapper Custom Type Converter not working
public class PagedViewModel<T>
{
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<T> Subset { get; set; }
}
寫打開通用轉換器從IPagedList<T>
到PagedViewModel<T>
來源:https://github.com/AutoMapper/AutoMapper/wiki/Open-Generics
public class Converter<TSource, TDestination> : ITypeConverter<IPagedList<TSource>, PagedViewModel<TDestination>>
{
public PagedViewModel<TDestination> Convert(IPagedList<TSource> source, PagedViewModel<TDestination> destination, ResolutionContext context)
{
return new PagedViewModel<TDestination>()
{
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<TSource>, IEnumerable<TDestination>>(source) //User mapper to go from "foo" to "bar"
};
}
}
配置映射器
new MapperConfiguration(cfg =>
{
cfg.CreateMap<RequestForQuote, RequestForQuoteViewModel>();//Define each object you need to map
cfg.CreateMap(typeof(IPagedList<>), typeof(PagedViewModel<>)).ConvertUsing(typeof(Converter<,>)); //Define open generic mapping
});
有人可以提供一個堅實的'PagedListTypeConverter'實現嗎? – 2012-09-12 12:52:09
特洛伊古德的PagedList工作TypeConverter成一個簡單的ViewModel可以在這裏找到:http://stackoverflow.com/questions/12470156/automapper-custom-type-converter-not-working/12538611#12538611 – 2012-09-21 21:49:05