AutoMapper映射可为空属性时触发空引用异常的问题排查
问题:AutoMapper映射可为空属性时触发NullReferenceException
尝试映射HomeTown属性(源路径:Person.NaturalPerson.HomeTown,目标路径:PersonDTO.NaturalPersonDTO.HomeTown),当源中该属性为null时,出现以下错误:
Mapping types: Person -> PersonDTO LogSistemas.Domynus.Application.Core.Entities.Person.Person -> LogSistemas.Domynus.Application.Core.Dto.Person.PersonDTO Type Map configuration: Person -> PersonDTO LogSistemas.Domynus.Application.Core.Entities.Person.Person -> LogSistemas.Domynus.Application.Core.Dto.Person.PersonDTO Destination Member: NaturalPerson ---> AutoMapper.AutoMapperMappingException: Error mapping types. Mapping types: NaturalPerson -> NaturalPersonDTO LogSistemas.Domynus.Application.Core.Entities.Person.NaturalPerson -> LogSistemas.Domynus.Application.Core.Dto.Person.NaturalPersonDTO Type Map configuration: NaturalPerson -> NaturalPersonDTO LogSistemas.Domynus.Application.Core.Entities.Person.NaturalPerson -> LogSistemas.Domynus.Application.Core.Dto.Person.NaturalPersonDTO Destination Member: HomeTown ---> System.NullReferenceException: Object reference not set to an instance of an object.
类定义
NaturalPerson实体类
public class NaturalPerson { public NaturalPerson() { HomeTown = new(); } public City HomeTown { get; set; } }
NaturalPersonDTO类
public class NaturalPersonDTO { public NaturalPersonDTO() { HomeTown = new CityDTO(); } public CityDTO HomeTown { get; set; } }
映射配置
CreateMap<Entities.Person.Person, PersonDTO>(); CreateMap<Entities.Person.NaturalPerson, NaturalPersonDTO>(); CreateMap<City, CityDTO>() .ConvertUsing(x => new CityDTO { Id = x.Id, StateId = x.StateId, Name = x.Name, State = x.State.Abbreviation, Country = x.State.Country.Name });
问题原因
AutoMapper本身支持null属性映射,但你在City到CityDTO的自定义转换逻辑中,既没处理源对象为null的情况,也没对x.State、x.State.Country这类嵌套属性做空引用检查。当HomeTown为null时,AutoMapper会把null传入ConvertUsing的委托参数x,此时访问x.Id、x.State等属性就会触发NullReferenceException。
解决方案
修改City到CityDTO的映射配置,添加null检查和空传播运算符,避免空引用:
CreateMap<City, CityDTO>() .ConvertUsing(x => { // 先判断源对象是否为null,返回null或默认实例(根据业务需求选择) if (x == null) return null; return new CityDTO { Id = x.Id, StateId = x.StateId, Name = x.Name, // 使用空传播运算符,避免x.State为null时触发异常 State = x.State?.Abbreviation, // 多层嵌套属性同样做空引用检查 Country = x.State?.Country?.Name }; });
另外,如果你的NaturalPerson实体是ORM框架(比如EF Core)生成的,可能存在构造函数未被执行的情况(比如从数据库查询时未加载导航属性),导致HomeTown为null。上述的null检查也能覆盖该场景。
内容的提问来源于stack exchange,提问作者Fernando Cristan
相关产品推荐
相关产品推荐

