【发布时间】:2011-11-30 06:37:08
【问题描述】:
当我尝试映射具有空字符串属性的对象时,目标也是空的。有没有我可以打开的全局设置,说所有空字符串都应该映射为空?
【问题讨论】:
标签: asp.net-mvc asp.net-mvc-3 automapper
当我尝试映射具有空字符串属性的对象时,目标也是空的。有没有我可以打开的全局设置,说所有空字符串都应该映射为空?
【问题讨论】:
标签: asp.net-mvc asp.net-mvc-3 automapper
这样的事情应该可以工作:
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());?这是我可以添加多个映射器的地方吗?
如果您需要一个非全局设置,并且希望针对每个属性进行设置:
Mapper.CreateMap<X, Y>()
.ForMember(
dest => dest.FieldA,
opt => opt.NullSubstitute(string.Empty)
);
【讨论】:
与 David Wick 的回答类似,您也可以将 ConvertUsing 与 lambda 表达式一起使用,这样就不需要额外的类。
Mapper.CreateMap<string, string>().ConvertUsing(s => s ?? string.Empty);
【讨论】: