我在Stack Overflow上搜索了一下,用谷歌搜索了一下,但我找不到任何关于这方面的帮助或建议。
我有一个如下所示的类,它创建一个PagedList对象,并使用AutoMappper将类型从源映射到目标。
public class PagedList<TSrc, TDest>
{
protected readonly List<TDest> _items = new List<TDest>();
public IEnumerable<TDest> Items {
get { return this._items; }
}
}我想为这种类型创建一个Map,将其转换为另一种类型,如下所示
public class PagedListViewModel<TDest>
{
public IEnumerable<TDest> Items { get; set; }
}我已经尝试过
Mapper.CreateMap<PagedList<TSrc, TDest>, PagedListViewModel<TDest>>();但是编译器会因为TSrc和TDest而抱怨
有什么建议吗?
发布于 2015-04-01 08:46:28
根据the AutoMapper wiki的说法
public class Source<T> {
public T Value { get; set; }
}
public class Destination<T> {
public T Value { get; set; }
}
// Create the mapping
Mapper.CreateMap(typeof(Source<>), typeof(Destination<>));在您的情况下,这将是
Mapper.CreateMap(typeof(PagedList<,>), typeof(PagedListViewModel<>));发布于 2016-10-08 16:19:35
这是一个最佳实践:
第一步:创建泛型类。
public class AutoMapperGenericsHelper<TSource, TDestination>
{
public static TDestination ConvertToDBEntity(TSource model)
{
Mapper.CreateMap<TSource, TDestination>();
return Mapper.Map<TSource, TDestination>(model);
}
}第二步:使用它
[HttpPost]
public HttpResponseMessage Insert(LookupViewModel model)
{
try
{
EducationLookup result = AutoMapperGenericsHelper<LookupViewModel, EducationLookup>.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));
}
}https://stackoverflow.com/questions/29380976
复制相似问题