使用AutoMapper映射实体到DTO时为何抛出NullReferenceException
问题:AutoMapper映射时抛出NullReferenceException且结果为空
我查了大量同类问题,还是搞不懂为什么会触发NullReferenceException。具体场景如下:
实体定义
SendCommentConfiguration(数据库实体)
public class SendCommentConfiguration { public int Id { get; set; } public string Configuration { get; set; } }
SendCommentConfigurationDTO(数据传输对象)
public class SendCommentConfigurationDTO { public int Id { get; set; } public string Configuration { get; set; } }
注:Configuration字段存储的是数据库中的JSON对象
AutoMapper映射配置
public class MapperProfiles : Profile { public MapperProfiles() { CreateMap<CommentDTO, Comment>().ReverseMap(); CreateMap<ReviewDTO, Review>().ReverseMap(); CreateMap<WebsiteDTO, Websites>().ReverseMap(); CreateMap<CommentGroupDTO, CommentGroup>().ReverseMap(); CreateMap<SendCommentConfigurationDTO, SendCommentConfiguration>().ReverseMap(); } }
映射执行代码
public async Task<IEnumerable<SendCommentConfigurationDTO>> GetAllSendRequests() { var result = await _reportsRepository.GetAllSendRequests(); var mappedResult = _mapper.Map<IEnumerable<SendCommentConfigurationDTO>>(result); return mappedResult; }
关键细节
result不为空,包含55条SendCommentConfiguration实体记录- 执行映射后
mappedResult为空,同时抛出NullReferenceException
可能的排查方向
- 检查
_mapper实例是否正确注入:如果依赖注入未配置AutoMapper,_mapper本身为null,调用Map方法会直接触发NullReferenceException - 确认AutoMapper是否加载了映射配置:启动时需确保将
MapperProfiles注册到AutoMapper,比如在Program.cs中添加builder.Services.AddAutoMapper(typeof(MapperProfiles)) - 测试单条记录映射:尝试单独映射
result中的某一条记录,排查是否是某条记录的Configuration字段为null导致的异常(AutoMapper默认支持null属性映射,除非有自定义转换逻辑) - 查看异常调用栈:定位NullReferenceException的具体触发位置,确认是Map方法内部报错,还是返回结果后调用方的问题
内容的提问来源于stack exchange,提问作者Pablo
相关产品推荐
相关产品推荐

