使用AutoMapper映射对象列表时遇类型转换错误求助
映射配置代码(MappingProfile.cs)
public class MappingProfile: Profile { public MappingProfile() { CreateMap<GraphUserDeltaApiDto, User>().ReverseMap(); } }
初始业务代码与错误
业务代码:
graphClient.CheckforUserDeltas(); var graphDtoUsers = graphClient.UserObjects; List<User> freshUsers = mapper.Map<List<GraphUserDeltaApiDto>>(graphDtoUsers);
抛出错误:
Microsoft.CSharp.RuntimeBinder.RuntimeBinderException
HResult=0x80131500
Message=Cannot implicitly convert type 'System.Collections.Generic.List<Core.Application.Contracts.DTOs.GraphUserDeltaApiDto>' to 'System.Collections.Generic.List<Core.Domain.Entities.User>'
修改后的代码与新错误
修改后的代码:
var Users = mapper.Map<List<User>,List<GraphUserDeltaApiDto>>(graphDtoUsers); var localSave = UpsertO3MWithLatestUserData(Users);
新错误:
Microsoft.CSharp.RuntimeBinder.RuntimeBinderException
HResult=0x80131500
Message=The best overloaded method match for 'AutoMapper.IMapperBase.Map<System.Collections.Generic.List<Core.Domain.Entities.User>,System.Collections.Generic.List<Core.Application.Contracts.DTOs.GraphUserDeltaApiDto>>(System.Collections.Generic.List<Core.Domain.Entities.User>)' has some invalid arguments
Source=System.Linq.Expressions
需求说明
已知AutoMapper会自动复制同名字段,当前源数据字段比目标多,需要解决映射报错问题。
修正映射调用的泛型参数
核心问题是搞反了AutoMapper映射的类型顺序:- 若使用
Map<TDestination>(source)重载,直接指定目标类型即可:List<User> freshUsers = mapper.Map<List<User>>(graphDtoUsers); - 若要明确指定源和目标类型,注意泛型参数顺序为源在前,目标在后:
List<User> freshUsers = mapper.Map<List<GraphUserDeltaApiDto>, List<User>>(graphDtoUsers);
- 若使用
确认源数据的实际类型
检查graphClient.UserObjects的返回类型是否为List<GraphUserDeltaApiDto>或兼容的可枚举类型(如IEnumerable<GraphUserDeltaApiDto>)。如果是其他类型,先转换为可枚举集合再映射,AutoMapper支持直接将IEnumerable映射为List。验证映射配置的有效性
在应用启动时添加配置验证,提前发现映射规则的问题:mapper.ConfigurationProvider.AssertConfigurationIsValid();默认情况下多余的源字段会被AutoMapper忽略,无需额外配置;如果需要严格校验字段映射,可以在创建映射时添加
ReverseMap().ForAllOtherMembers(opt => opt.Ignore())或者开启全局严格模式。
内容的提问来源于stack exchange,提问作者dot

