AutoMapper三层结构反向映射生成‘幽灵’对象问题咨询
AutoMapper反向映射空值问题解决方案
我们需要将Order -可选关联-> Customer -关联-> Address的三层嵌套实体结构,扁平化为以各实体模型作为根属性的FlatModel,定义如下:
public class FlatModel { public OrderModel Order { get; set; } public CustomerModel Customer { get; set; } public AddressModel CustomerAddress { get; set; } }
原映射配置如下,正向扁平映射工作正常:
public class FlatModelProfile : Profile { public FlatModelProfile() { CreateMap<Order, OrderModel>().ReverseMap(); CreateMap<Customer, CustomerModel>().ReverseMap(); CreateMap<Address, AddressModel>().ReverseMap(); CreateMap<Order, FlatModel>() .ForMember(m => m.Order, opt => opt.MapFrom(p => p)) .ForMember(m => m.Customer, opt => opt.MapFrom(p => p.Customer)) .ForMember(m => m.CustomerAddress, opt => opt.MapFrom(p => p.Customer.Address)) .ReverseMap(); } }
但反向映射时存在问题:当FlatModel的Customer属性为null时,映射后的Order对象的Customer属性仍会被初始化为空实例,而非保持null。
解决方案
问题根源是AutoMapper默认会自动初始化嵌套类型的实例,即使源属性为null。需要修改反向映射的配置,明确指定当源属性为null时,目标属性保持null:
修改后的映射配置代码:
public class FlatModelProfile : Profile { public FlatModelProfile() { CreateMap<Order, OrderModel>().ReverseMap(); CreateMap<Customer, CustomerModel>().ReverseMap(); CreateMap<Address, AddressModel>().ReverseMap(); CreateMap<Order, FlatModel>() .ForMember(m => m.Order, opt => opt.MapFrom(p => p)) .ForMember(m => m.Customer, opt => opt.MapFrom(p => p.Customer)) .ForMember(m => m.CustomerAddress, opt => opt.MapFrom(p => p.Customer?.Address)) // 避免空引用异常 .ReverseMap() // 配置Order.Customer的反向映射规则 .ForMember(dest => dest.Customer, opt => { // 仅当FlatModel.Customer不为null时才执行映射 opt.Condition(src => src.Customer != null); // 直接映射源属性,源为null则目标为null opt.MapFrom(src => src.Customer); }) // 配置Customer.Address的反向映射规则 .ForMember(dest => dest.Customer.Address, opt => { // 仅当FlatModel.Customer和CustomerAddress都不为null时才映射 opt.Condition(src => src.Customer != null && src.CustomerAddress != null); opt.MapFrom(src => src.CustomerAddress); }); } }
关键说明
- 使用
Condition确保只有源属性有效时才执行映射,阻止AutoMapper自动创建空实例 - 正向映射中改用
p.Customer?.Address,避免原Order的Customer为null时抛出空引用异常 - 对
Customer.Address的额外配置,避免Customer存在但CustomerAddress为null时,AutoMapper初始化Address空实例
内容的提问来源于stack exchange,提问作者LueTm
相关产品推荐
相关产品推荐

