[英]AutoMapper - Map flatten object to complex object
我有這些模型:
class Source
{
String A;
String B;
String C;
String D;
}
class Destination
{
String A;
String B;
Another another;
Other other;
}
class Other
{
String C;
AnotherOne Another;
}
class AnotherOne
{
String D;
}
我想 map Source
model 到Destination
及其子級。 嘗試使用 AutoMapper 的第一種方法。 那么有可能嗎? 還是手動完成這項任務更好?
解決方案 1:使用ForPath
。
var config = new MapperConfiguration(cfg =>
{
cfg.CreateMap<Source, AnotherOne>();
cfg.CreateMap<Source, Other>()
.ForPath(dest => dest.Another, opt => opt.MapFrom(src => src));
cfg.CreateMap<Source, Destination>()
.ForPath(dest => dest.other, opt => opt.MapFrom(src => src));
});
解決方案 2:使用IncludeMembers
展ReverseMap
顯式創建反向 map。
var config = new MapperConfiguration(cfg =>
{
cfg.CreateMap<Source, AnotherOne>()
.ReverseMap();
cfg.CreateMap<Other, Source>()
.IncludeMembers(src => src.Another)
.ReverseMap();
cfg.CreateMap<Destination, Source>()
.IncludeMembers(src => src.other)
.ReverseMap();
});
參考
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.