AutoMapper, Call Mapper.Map() inside a custom type converter?

对着背影说爱祢 提交于 2019-12-10 23:06:01

问题


I am currently testing with AutoMapper, but i currently have a case where the property names do not match each other, so a custom type convert was needed. But when i use the custom type converter, i have to map all other properties manually? i can't call another Map inside the type converter ofcourse as this will cause a overflow.

This is unwanted as there are at most 3 model specific properties that do not match per model so i DO want the other properties to be automaticaly mapped.

Could anyone point me in the right direction for this one?


回答1:


You don't need to use a custom type converter to map classes where there a few properties that simply have names that don't match. Custom type converters are for when you need to, as they say, "take complete control over the conversion of one type to another".

Set up the map with CreateMap() and then set some extra rules using ForMember(), like this:

Mapper.CreateMap<Person, Customer>()
    .ForMember(dest => dest.Surname, opt => opt.MapFrom(src => src.LastName))
    .ForMember(dest => dest.DateOfBirth, opt => opt.MapFrom(src => src.DOB));

This maps LastName and DOB from the source Person class to the Surname and DateOfBirth properties of the destination Customer class.



来源:https://stackoverflow.com/questions/11883412/automapper-call-mapper-map-inside-a-custom-type-converter

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!