[英]Default mapping configuration for inherited classes in AutoMapper
Is it possible to create a default destination mapping in AutoMapper ? 是否可以在AutoMapper中创建默认的目标映射?
Source classes: 源类:
class SourceA {
public string X { get; set; }
}
class SourceB {
public string Y { get; set; }
}
Destination classes: 目标类别:
class DestBase {
public List<string> Z { get; set; }
}
class DestA : DestBase {
public string X { get; set; }
}
class DestB : DestBase {
public string Y { get; set; }
}
And the mapping configuration contains the following: 映射配置包含以下内容:
cfg.CreateMap<SourceA, DestA>()
.ForMember(dest => dest.Z, src => src.MapFrom(s => null));
cfg.CreateMap<SourceB, DestB>()
.ForMember(dest => dest.Z, src => src.MapFrom(s => null));
Is it possible to create a default mapping for all destination classes inheriting the DestBase
to avoid the repeated .ForMember(...)
lines ? 是否可以为所有继承
DestBase
目标类创建默认映射,以避免重复的.ForMember(...)
行?
eg. 例如。 something like:
就像是:
cfg.CreateMap<object, DestBase>
.ForMember(dest => dest.Z, src => src.MapFrom(s => new List<string>()));
In principle yes, with the Include
method, but there is a caveat. 原则上可以,使用
Include
方法可以,但有一个警告。
If you define a map from source type object
, this map would match all types. 如果您从源类型
object
定义映射,则此映射将匹配所有类型。 Maybe you can introduce an interface ISource
for the source types that should be affected by this mapping. 也许您可以为应该受此映射影响的源类型引入接口
ISource
。
So it could look like this: 所以看起来可能像这样:
class SourceA : ISource {
public string X { get; set; }
}
class SourceB : ISource {
public string Y { get; set; }
}
cfg.CreateMap<ISource, DestBase>
.Include<SourceA, DestA>
.Include<SourceB, DestB>
.Include<SourceC, DestC>
.ForMember(dest => dest.Z, , o => o.MapFrom(src => new List<string>()));
cfg.CreateMap<SourceA, DestA>()
.ForMember(dest => dest.X, o => o.MapFrom(src => src.X));
cfg.CreateMap<SourceB, DestB>()
.ForMember(dest => dest.Y, o => o.MapFrom(src => src.Y));
// still need to create a map even if no additional properties are to be mapped
cfg.CreateMap<SourceC, DestC>();
Note that you still need to create maps for all included types, even if there are no additional properties to map. 请注意,即使没有要映射的其他属性,您仍需要为所有包含的类型创建映射。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.