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

如何通过AutoMapper将所有可空类型属性映射为空字符串?

AutoMapper批量映射可空类型到字符串并替换Null为空字符串

实现方案

无需手写反射,利用AutoMapper的ForAllMembers方法,在特定映射配置中批量处理符合条件的属性,既不用逐个配置,也不会影响其他映射的null→null规则。

代码实现

  1. 配置专属映射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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.01 04:33:20