Automapper将空字符串清空

Sha*_*ean 12 asp.net-mvc automapper asp.net-mvc-3

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

Dav*_*ick 22

这样的事情应该有效:

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

在您的配置类中:

public class AutoMapperConfiguration
{
    public static void Configure()
    {
        Mapper.CreateMap<string, string>().ConvertUsing<NullStringConverter>();

        Mapper.AddProfile(new SomeViewModelMapper());
        Mapper.AddProfile(new SomeOtherViewModelMapper());
        ...
    }
}
Run Code Online (Sandbox Code Playgroud)


Nic*_*ski 15

如果您需要非全局设置,并希望每个属性执行此操作:

Mapper.CreateMap<X, Y>()
.ForMember(
    dest => dest.FieldA,
    opt => opt.NullSubstitute(string.Empty)
);
Run Code Online (Sandbox Code Playgroud)


Joe*_*Joe 11

与David Wick的答案类似,您也可以使用ConvertUsinglambda表达式,这样就无需额外的类.

Mapper.CreateMap<string, string>().ConvertUsing(s => s ?? string.Empty);
Run Code Online (Sandbox Code Playgroud)