如何使用AutoMapper将单个值映射为集合?
如何用AutoMapper实现标量到集合的映射?
我有以下源类:
public class SourcePerson { public Ethnicity Ethnicity { get; set; } } public enum Ethnicity {}
需要将其映射到目标类:
public class DestinationPerson { public EthnicityType[] Ethnicities { get; set; } } public enum EthnicityType {}
场景背景:
我通过xsd.exe工具从两份XSD文件自动生成了上述C#类:
- 源XSD:
<xs:element name="Ethnicity" type="Ethnicity" minOccurs="1" maxOccurs="1" />
- 目标XSD:
<xs:element name="Ethnicities" maxOccurs="1" minOccurs="1"> <xs:complexType> <xs:sequence> <xs:element name="Ethnicity" type="EthnicityType" minOccurs="1" maxOccurs="5" /> </xs:sequence> </xs:complexType> </xs:element>
现在需要把符合源XSD的XML反序列化得到的SourcePerson实例,通过AutoMapper映射为DestinationPerson实例,但官方文档只提到集合间的映射,没说明标量到集合的配置方式。
配置步骤
1. 先配置枚举类型的映射
Ethnicity和EthnicityType是不同枚举,需先让AutoMapper明确两者的转换规则:
- 如果枚举成员名称完全一致,AutoMapper会自动匹配;
- 如果名称不匹配,需要手动指定对应关系。
// 基础枚举映射 CreateMap<Ethnicity, EthnicityType>(); // 若枚举成员名称不匹配,添加自定义映射示例 // .ForMember(dest => dest.TargetEnumValue, opt => opt.MapFrom(src => src.SourceEnumValue));
2. 配置实体类的标量到集合映射
通过MapFrom方法,将源对象的单个Ethnicity属性转换为包含单个元素的EthnicityType数组:
// 实体类映射配置 CreateMap<SourcePerson, DestinationPerson>() .ForMember(dest => dest.Ethnicities, opt => opt.MapFrom(src => new[] { src.Ethnicity }) );
完整配置示例
var configuration = new MapperConfiguration(cfg => { // 枚举映射 cfg.CreateMap<Ethnicity, EthnicityType>(); // 实体映射 cfg.CreateMap<SourcePerson, DestinationPerson>() .ForMember(dest => dest.Ethnicities, opt => opt.MapFrom(src => new[] { src.Ethnicity }) ); }); // 开发阶段验证配置合法性(可选) configuration.AssertConfigurationIsValid(); // 使用映射 var mapper = configuration.CreateMapper(); SourcePerson source = new SourcePerson { Ethnicity = Ethnicity.XXX }; DestinationPerson destination = mapper.Map<DestinationPerson>(source);
空值处理(可选)
如果源对象的Ethnicity可能为null,可添加空值判断避免异常:
.ForMember(dest => dest.Ethnicities, opt => opt.MapFrom(src => src.Ethnicity != null ? new[] { src.Ethnicity } : Array.Empty<EthnicityType>()) );
内容的提问来源于stack exchange,提问作者Jason 'Bug' Fenter
相关产品推荐
相关产品推荐

