AutoMapper通用映射

我已经在StackOverflow上搜索并搜索了它,但我还没有找到任何帮助或建议。

我有一个像下面这样的类创建一个PagedList对象,并使用AutoMappper将类型从源映射到目标

 public class PagedList { protected readonly List _items = new List(); public IEnumerable Items { get { return this._items; } } } 

我想为这种类型创建一个Map,它应该将它转换为另一种类型,如下所示

 public class PagedListViewModel { public IEnumerable Items { get; set; } } 

我试过了

 Mapper.CreateMap<PagedList, PagedListViewModel>(); 

但编译器因TSrcTDestTDest

有什么建议吗?

根据AutoMapper维基 :

 public class Source { public T Value { get; set; } } public class Destination { public T Value { get; set; } } // Create the mapping Mapper.CreateMap(typeof(Source<>), typeof(Destination<>)); 

在你的情况下,这将是

 Mapper.CreateMap(typeof(PagedList<,>), typeof(PagedListViewModel<>)); 

这是最佳做法:

第一步:创建一个generice类。

 public class AutoMapperGenericsHelper { public static TDestination ConvertToDBEntity(TSource model) { Mapper.CreateMap(); return Mapper.Map(model); } } 

第二步:使用它

 [HttpPost] public HttpResponseMessage Insert(LookupViewModel model) { try { EducationLookup result = AutoMapperGenericsHelper.ConvertToDBEntity(model); this.Uow.EducationLookups.Add(result); Uow.Commit(User.Id); return Request.CreateResponse(HttpStatusCode.OK, result); } catch (DbEntityValidationException e) { return Request.CreateResponse(HttpStatusCode.InternalServerError, CustomExceptionHandler.HandleDbEntityValidationException(e)); } catch (Exception ex) { return Request.CreateResponse(HttpStatusCode.BadRequest, ex.HResult.HandleCustomeErrorMessage(ex.Message)); } }