我有这些型号:
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;
}
我想将Source
模型映射到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));
});
演示解决方案1@.NET Fiddle
解决方案2:使用IncludeMembers
来压平,使用ReverseMap
来显式创建反向映射
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();
});
演示解决方案2@.NET Fiddle
参考
展平(IncludeMembers部分(-AutoMapper文档