【发布时间】:2021-11-08 21:03:05
【问题描述】:
您好,我一直在使用 AutoMapper 转换我的对象,现在我正在尝试将两个嵌套对象合并为一个,但我不知道该怎么做。
我有以下代码:
这些是我的源对象
class SourceSubItemA
{
string subPropertyA;
}
class SourceSubItemB
{
string subPropertyB;
}
class Source
{
SourceSubItemA subItemA;
SourceSubItemB subItemB;
}
目标对象
class DestinationSubItem
{
string propertyA;
string propertyB;
}
class Destination
{
DestinationSubItem destItem;
}
这是我的 Automapper 配置
Mapper.CreateMap<SourceSubItemA, DestinationSubItem>()
.ForMember(dest => propertyA, opt => opt.MapFrom(src => src.subPropertyA));
Mapper.CreateMap<SourceSubItemB, DestinationSubItem>()
.ForMember(dest => propertyB, opt => opt.MapFrom(src => src.subPropertyB));
// Probably I have to do something more here.
Mapper.CreateMap<Source, Destination>()
.ForMember(dest => dest.destItem, opt => opt.MapFrom(src => src.subItemA));
最后我用这种方式使用映射器
Mapper.Map<Destination>(sourceObject);
预期的结果必须是一个 Destination 对象,其子项同时填充了两个属性。
请帮忙!
【问题讨论】:
标签: c# automapper