映射Object2至Object1时遇Unsupported mapping Error,求排查解决
问题:AutoMapper映射Object2到Object1时提示缺少类型映射配置
- 尝试将Object2映射为Object1时触发500错误,始终找不到原因
- 试过两种写法均报错:
Object1 obj1 = this._mapper.Map<Object1>(new Object2());//var obj1 = _mapper.Map<Object1>(request.Object2); - 收到的错误信息:
type": "https://httpstatuses.com/500",
"title": "Internal Server Error",
"status": 500,
"detail": "Missing type map configuration or unsupported mapping.Mapping types:
Object -> Object1 ...... -> ......"
解决方案
这个错误核心是未配置Object2到Object1的映射规则,或配置未被正确加载,按以下步骤排查:
添加映射配置类
必须创建AutoMapper的Profile类定义映射关系,示例:public class ObjectMappingProfile : Profile { public ObjectMappingProfile() { // 属性名一致时自动匹配的基础映射 CreateMap<Object2, Object1>(); // 若属性名不一致,手动指定映射规则 // CreateMap<Object2, Object1>() // .ForMember(dest => dest.TargetProperty, opt => opt.MapFrom(src => src.SourceProperty)); } }确保配置被AutoMapper加载
- ASP.NET Core项目:在Program.cs/Startup.cs中注册Profile
builder.Services.AddAutoMapper(typeof(ObjectMappingProfile)); - 手动初始化场景:
var mapperConfig = new MapperConfiguration(cfg => { cfg.AddProfile<ObjectMappingProfile>(); }); var mapper = mapperConfig.CreateMapper();
- ASP.NET Core项目:在Program.cs/Startup.cs中注册Profile
验证配置有效性
启动时添加配置验证,提前发现问题:mapperConfig.AssertConfigurationIsValid();这会检查所有映射的属性是否都有匹配规则,避免运行时踩坑。
检查传入对象的实际类型
错误信息显示Object -> Object1,可能你传入的不是Object2,而是它的父类Object。确认request.Object2的实际类型与映射配置中的源类型一致,避免因多态导致的类型不匹配。
内容的提问来源于stack exchange,提问作者awthz Zei
相关产品推荐
相关产品推荐

