嗨,我一直在使用 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 物件,其中的子項同時填充了這兩個屬性。
請幫忙!
uj5u.com熱心網友回復:
正如我所看到的,Destination只是它的一個包裝器,DestinationSubItem它是真正需要從Source.
在這種情況下,您可以定義一個映射器 from SourcetoDestination將dest.destItem映射結果Source直接放入to DestinationSubItem。
這里有一個例子:
Mapper.CreateMap<Source, Destination>()
.ForMember(dest => dest.destItem, opt => opt.MapFrom(src => Mapper.Map<DestinationSubItem>(src));
Mapper.CreateMap<Source, DestinationSubItem>()
.ForMember(dest => dest.propertyA, opt => opt.MapFrom(src => src.subItemA.subPropertyA)
.ForMember(dest => dest.propertyB, opt => opt.MapFrom(src => src.subItemB.subPropertyB);
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/353472.html
下一篇:將一個結構的成員復制到另一個C#
