【问题标题】:Automapper null string to emptyAutomapper空字符串为空
【发布时间】:2011-11-30 06:37:08
【问题描述】:

当我尝试映射具有空字符串属性的对象时,目标也是空的。有没有我可以打开的全局设置,说所有空字符串都应该映射为空?

【问题讨论】:

    标签: asp.net-mvc asp.net-mvc-3 automapper


    【解决方案1】:

    这样的事情应该可以工作:

    public class NullStringConverter : ITypeConverter<string, string>
      {
        public string Convert(string source)
        {
          return source ?? string.Empty;
        }
      }
    

    在你的配置类中:

    public class AutoMapperConfiguration
    {
        public static void Configure()
        {
            Mapper.CreateMap<string, string>().ConvertUsing<NullStringConverter>();
    
            Mapper.AddProfile(new SomeViewModelMapper());
            Mapper.AddProfile(new SomeOtherViewModelMapper());
            ...
        }
    }
    

    【讨论】:

    • 什么是:Mapper.AddProfile(new SomeViewModelMapper());?这是我可以添加多个映射器的地方吗?
    【解决方案2】:

    如果您需要一个非全局设置,并且希望针对每个属性进行设置:

    Mapper.CreateMap<X, Y>()
    .ForMember(
        dest => dest.FieldA,
        opt => opt.NullSubstitute(string.Empty)
    );
    

    【讨论】:

      【解决方案3】:

      与 David Wick 的回答类似,您也可以将 ConvertUsing 与 lambda 表达式一起使用,这样就不需要额外的类。

      Mapper.CreateMap<string, string>().ConvertUsing(s => s ?? string.Empty);
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2020-10-01
        • 2014-11-12
        • 1970-01-01
        • 2014-03-23
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多