Csharp/C#教程:AutoMapper通用映射分享


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); } } 

第二步:使用它

上述就是C#学习教程:AutoMapper通用映射分享的全部内容,如果对大家有所用处且需要了解更多关于C#学习教程,希望大家多多关注—计算机技术网(www.ctvol.com)!

 [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)); } } 

本文来自网络收集,不代表计算机技术网立场,如涉及侵权请联系管理员删除。

ctvol管理联系方式QQ:251552304

本文章地址:https://www.ctvol.com/cdevelopment/959515.html

(0)
上一篇 2021年11月23日
下一篇 2021年11月23日

精彩推荐