AutoMapper,在自定义类型转换器中调用Mapper.Map()吗? [英] AutoMapper, Call Mapper.Map() inside a custom type converter?
问题描述
我目前正在使用AutoMapper进行测试,但是我目前遇到一种情况,即属性名称彼此不匹配,因此需要自定义类型转换. 但是,当我使用自定义类型转换器时,是否必须手动映射所有其他属性?我无法在课程类型转换器中调用另一个Map,因为这会导致溢出.
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.
这是不必要的,因为每个模型最多有3个特定于模型的属性不匹配,因此我希望其他属性可以自动映射.
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?
推荐答案
您不需要使用自定义类型转换器来映射类,在该类中有一些属性仅具有名称不匹配的属性.自定义类型转换器适用于如他们所说,完全控制从一种类型到另一种类型的转换."
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".
使用CreateMap()
设置地图,然后使用ForMember()
设置一些附加规则,如下所示:
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));
这会将LastName
和DOB
从源Person
类映射到目标Customer
类的Surname
和DateOfBirth
属性.
This maps LastName
and DOB
from the source Person
class to the Surname
and DateOfBirth
properties of the destination Customer
class.
这篇关于AutoMapper,在自定义类型转换器中调用Mapper.Map()吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!