如何用Automapper将SampleDto多IEnumerable<int>属性映射为SampleModel集合
实现方案
该场景属于典型的集合拆分映射:需要把源对象中三个独立的整数集合,逐元素拆解为独立的目标实体,同时给每个实体绑定固定的外部上下文常量值,最终合并为统一的模型集合。
首先需要先修正原示例代码的基础问题:
- 原代码中
SampleDto的三个属性是IEnumerable<int>类型,直接new对象后属性值为null,且IEnumerable本身不提供Add方法,直接调用会触发空引用异常。实际使用时需要先给每个属性初始化为具体的可修改集合(比如List<int>)再添加元素。
映射配置实现
因为目标集合是从源对象拆分拼接生成的,无法使用AutoMapper默认的成员匹配规则,需要通过自定义值转换器实现映射逻辑,同时把外部的pk、三个ptype常量作为映射参数传入,避免硬编码到配置中:
public class AutoMapperProfile : Profile { public AutoMapperProfile() { // 定义从SampleDto到目标集合的转换规则 CreateMap<SampleDto, IEnumerable<SampleModel>>() .ConvertUsing((source, destination, context) => { // 从映射上下文取出外部传入的常量参数 var externalParams = context.Items; var commonPk = (int?)externalParams["pk"]; var type1 = (int?)externalParams["ptype1"]; var type2 = (int?)externalParams["ptype2"]; var type3 = (int?)externalParams["ptype3"]; var modelList = new List<SampleModel>(); // 逐组拆分每个属性的集合,生成独立模型 if (source.Property1 != null) { modelList.AddRange(source.Property1.Select(item => new SampleModel { Id = commonPk, TypeId = type1, Values = item })); } if (source.Property2 != null) { modelList.AddRange(source.Property2.Select(item => new SampleModel { Id = commonPk, TypeId = type2, Values = item })); } if (source.Property3 != null) { modelList.AddRange(source.Property3.Select(item => new SampleModel { Id = commonPk, TypeId = type3, Values = item })); } return modelList; }); } }
映射执行逻辑
执行映射时,把需要传入的外部常量值通过Items参数注入,完成最终转换:
// 初始化Mapper实例 var mapperConfig = new MapperConfiguration(cfg => cfg.AddProfile<AutoMapperProfile>()); var mapper = mapperConfig.CreateMapper(); // 初始化源对象(修正原代码的空引用问题) var sampleDto = new SampleDto { Property1 = new List<int> {11, 12, 13}, Property2 = new List<int> {21, 22, 23}, Property3 = new List<int> {31, 32, 33} }; // 执行映射,传入外部常量值 var result = mapper.Map<IEnumerable<SampleModel>>(sampleDto, opt => { opt.Items["pk"] = (int?)100; opt.Items["ptype1"] = (int?)51; opt.Items["ptype2"] = (int?)52; opt.Items["ptype3"] = (int?)53; });
最终生成的结果结构和题目要求的输出完全一致:同属一个属性的集合元素会绑定对应的TypeId,所有元素共用传入的pk值,逐元素展开为独立的SampleModel实例。
注意事项
- 不要依赖AutoMapper的默认扁平映射规则实现这类一对多拆分逻辑:默认规则仅支持源对象单值到目标对象单值的匹配,无法完成集合拆分、批量生成目标实体的操作
- 外部上下文的动态常量值不要硬编码在Profile配置中,通过上下文Items传入可以保证映射规则的通用性,适配不同业务场景下的常量值
- 映射过程中需要对源集合做空值判断,避免源属性为null时触发空引用异常
内容的提问来源于stack exchange,提问作者Byron Scott
相关产品推荐
相关产品推荐

