.NET Core 6中AutoMapper映射Dictionary<int,string>为强类型集合报错
.NET 6 AutoMapper字典转强类型集合映射错误排查方案
核心错误点
- 映射目标类型传参错误:调用
Map方法时泛型参数写的是ICollection<AIMConfigProfile>,AIMConfigProfile是AutoMapper的配置类,并非定义的实体类,目标集合元素类型应为AIMSchema - 单元素映射逻辑错误:配置映射规则时使用
source.ContainsKey(1)/source.ContainsKey(2),返回值是布尔类型,无法直接赋值给DateTime、string类型的属性,需要在判断Key存在后取对应字典值,同时做类型兼容处理 - 隐式依赖未校验:未确认AutoMapper启动时是否正确加载了自定义Profile,也未校验字典值的格式是否符合目标属性类型要求
原始报错信息
Error mapping types. Mapping types: List`1 -> ICollection`1 System.Collections.Generic.List`1[[System.Collections.Generic.Dictionary`2[[System.Int32, System.Private.CoreLib, Version=6.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e],[System.String, System.Private.CoreLib, Version=6.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e]], System.Private.CoreLib, Version=6.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e]]
问题相关原始代码
实体类定义
public class AIMSchema { public DateTime TransactionDate { get; set; } public string MachineCode { get; set; } }
错误的Profile配置
public class AIMConfigProfile : Profile { public AIMConfigProfile() { CreateMap<Dictionary<int, string>, AIMSchema>() .ForMember(dest => dest.TransactionDate, opt => opt.MapFrom(source => source.ContainsKey(1))) .ForMember(dest => dest.MachineCode, opt => opt.MapFrom(source => source.ContainsKey(2))) ; } }
错误的调用代码
var ff = _ambientState.Mapper.Map<ICollection<AIMConfigProfile>>(filteredStructuredData);
修复方案
第一步:修正Profile映射规则
把布尔判断替换为实际取值+类型校验逻辑,避免类型不匹配和空引用问题:
public class AIMConfigProfile : Profile { public AIMConfigProfile() { CreateMap<Dictionary<int, string>, AIMSchema>() .ForMember( dest => dest.TransactionDate, opt => opt.MapFrom(source => // 校验key存在且值为合法日期格式,否则赋值默认值 source.ContainsKey(1) && DateTime.TryParse(source[1], out var transDate) ? transDate : default(DateTime))) .ForMember( dest => dest.MachineCode, opt => opt.MapFrom(source => // 校验key存在则取值,否则赋值空字符串 source.ContainsKey(2) ? source[2] : string.Empty)); } }
第二步:修正映射调用的泛型参数
目标集合的元素类型替换为实际实体类AIMSchema:
// 确认filteredStructuredData是IEnumerable<Dictionary<int,string>>类型 var ff = _ambientState.Mapper.Map<ICollection<AIMSchema>>(filteredStructuredData);
第三步:校验配置加载
确认程序启动时已正确加载自定义Profile,在Program.cs服务注册阶段添加AutoMapper注入时,指定Profile所在的程序集:
// 加载AIMConfigProfile所在程序集的所有AutoMapper配置 builder.Services.AddAutoMapper(typeof(AIMConfigProfile));
额外注意事项
- 如果字典中key=1对应的日期值有固定格式(比如
yyyyMMdd、yyyy-MM-dd HH:mm:ss),建议把DateTime.TryParse替换为DateTime.TryParseExact指定格式,避免因区域性格式差异导致日期解析失败 - 如果业务要求日期/MachineCode为必填项,可以在映射逻辑中抛出明确的业务异常,代替默认值赋值,方便排查上游数据源问题
内容的提问来源于stack exchange,提问作者K.Z
相关产品推荐
相关产品推荐

