You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.09 23:40:58