如何通过AutoMapper将所有可空类型属性映射为空字符串?
AutoMapper批量映射可空类型到字符串并替换Null为空字符串
实现方案
无需手写反射,利用AutoMapper的ForAllMembers方法,在特定映射配置中批量处理符合条件的属性,既不用逐个配置,也不会影响其他映射的null→null规则。
代码实现
- 配置专属映射Profile
public class SourceToDtoProfile : Profile { public SourceToDtoProfile() { CreateMap<SourcePoco, TargetDto>() .ForAllMembers(opt => { // 筛选:源是可空值类型、目标是string的属性 var isNullableValueType = opt.SourceType.IsGenericType && opt.SourceType.GetGenericTypeDefinition() == typeof(Nullable<>); if (isNullableValueType && opt.DestinationType == typeof(string)) { opt.MapFrom(src => { var value = opt.SourceMember.GetValue(src); return value != null ? value.ToString() : string.Empty; }); } // 其他属性保持默认映射逻辑 }); } }
关键说明
- 仅针对
SourcePoco到TargetDto的映射生效,全局配置不受影响,不会破坏其他合法的null→null映射。 - 通过类型判断自动匹配所有
DateTime?、bool?等可空值类型属性,批量应用转换规则,无需逐个定义属性映射。 - 可空类型非null值直接转字符串,null值统一替换为空字符串。
内容的提问来源于stack exchange,提问作者Jan Drozen
相关产品推荐
相关产品推荐

