[英]AutoMapper generic mapping
I have searched on Stack Overflow and googled about it but I haven't been able to find any help or suggestion on this.我已经在 Stack Overflow 上搜索过并在谷歌上搜索过,但我找不到任何帮助或建议。
I have a class like the following which create a PagedList
object and also uses AutoMappper to map types from source to destination.我有一个类似下面的类,它创建一个
PagedList
对象,并且还使用 AutoMappper 将类型从源映射到目标。
public class PagedList<TSrc, TDest>
{
protected readonly List<TDest> _items = new List<TDest>();
public IEnumerable<TDest> Items {
get { return this._items; }
}
}
I would like to create a Map for this type that should convert it to another type like the following我想为这种类型创建一个地图,应该将其转换为另一种类型,如下所示
public class PagedListViewModel<TDest>
{
public IEnumerable<TDest> Items { get; set; }
}
I have tried with我试过
Mapper.CreateMap<PagedList<TSrc, TDest>, PagedListViewModel<TDest>>();
but the compiler complains because of TSrc
and TDest
但是编译器会因为
TSrc
和TDest
而TDest
Any suggestion?有什么建议吗?
According to the AutoMapper wiki :根据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<>));
In your case this would be在你的情况下,这将是
Mapper.CreateMap(typeof(PagedList<,>), typeof(PagedListViewModel<>));
This is a best practice:这是最佳实践:
first step: create a generice class.第一步:创建一个泛型类。
public class AutoMapperGenericsHelper<TSource, TDestination>
{
public static TDestination ConvertToDBEntity(TSource model)
{
Mapper.CreateMap<TSource, TDestination>();
return Mapper.Map<TSource, TDestination>(model);
}
}
Second step: Do Use it第二步:使用它
[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));
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.