我有一个类似这样的DTO:
class TypeDto
{
int Id {get; set;}
string Name {get; set;}
string DisplayName {get; set;}
IEnumerable<TypeDto> Children {get; set;}
}
现在我需要从两个不同的来源映射到它。因为其中一个包含
Name
另一个包含
DisplayName
. 所以类型:
class Type1
{
int Id {get; set;}
string Name {get; set;}
IEnumerable<Type1> Children {get; set;}
}
class Type2
{
int Id {get; set;}
string DisplayName {get; set;}
IEnumerable<Type2> Nested {get; set;}
}
注意在
Children
/
Nested
可枚举的
现在我要做的是地图:
config.CreateMap<Type1, TypeDto>();
config.CreateMap<Type2, TypeDto>()
.ForMember(dest => dest.Children, opts => opts.MapFrom(src => src.Nested));
var dto = _mapper.Map<TypeDto>(type1Instance);
_mapper.Map(type2Instance, dto);
第一个映射按预期工作,以递归方式映射子映射,填充
Id
和
名字
字段和离开
显示名称
等于
null
到处都是。然而,第二张地图填充了
显示名称
对于根对象,但在其子对象中,它会使
名字
字段。例如:
var type1Instance = new Type1
{
Id = 1,
Name = "root",
Children = new[] { new Type1
{
Id = 2,
Name = "child"
}}
};
var type2Instance = new Type2
{
Id = 1,
DisplayName = "Root",
Children = new[] { new Type2
{
Id = 2,
DisplayName = "Child"
}}
};
映射以下实例后,结果的字段设置为:
Id = 1,
Name = "root",
DisplayName = "Root",
Children = { TypeDto { Id = 2, Name = null, DisplayName = "Child", Children = null } }
所以孩子的
名字
是无效的,这不是我想要的。我希望它是
"child"
很明显。我应该如何配置映射器以获得想要的行为?
我不能改变
Type1
或
Type2
类,它们来自外部API。
automapper的版本是6.2.1,.NET Framework 4.5.1。