Asp.net-Mvc

Automapper空字元串為空

  • October 7, 2014

當我嘗試映射具有空字元串屬性的對象時,目標也是空的。我可以打開一個全域設置,說明所有空字元串都應該映射為空嗎?

像這樣的東西應該​​工作:

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.CreateMap<X, Y>()
.ForMember(
   dest => dest.FieldA,
   opt => opt.NullSubstitute(string.Empty)
);

引用自:https://stackoverflow.com/questions/7641298