在Automapper中,你可以使用ForMember
方法来指定源属性映射到目标属性。如果在映射过程中,源属性的值为null,则可以使用NullSubstitute
方法来指定在目标属性中使用的值。
例如,下面的代码片段将source.Name
属性映射到destination.Name
属性,如果source.Name
为null,则使用"Unknown"
作为默认值。
var config = new MapperConfiguration(cfg =>
{
cfg.CreateMap()
.ForMember(dest => dest.Name, opt => opt.NullSubstitute("Unknown"));
});
var source = new Source
{
Name = null
};
var mapper = config.CreateMapper();
var destination = mapper.Map(source);
Console.WriteLine(destination.Name); // 输出:Unknown
如果在映射完成后想要反转空替代的效果,可以使用ReverseMap
方法来反转源和目标类型的映射,并删除原始映射中使用的NullSubstitute
方法。
例如,下面的代码片段重新定义了config
对象,并使用ReverseMap
方法来反转源和目标类型的映射。
var config = new MapperConfiguration(cfg =>
{
cfg.CreateMap()
.ForMember(dest => dest.Name, opt => opt.NullSubstitute("Unknown"))
.ReverseMap();
});
var source = new Source
{
Name = null
};
var mapper = config.CreateMapper();
var destination = mapper.Map(new Destination { Name = "John" });
mapper.Map(source, destination);
Console.WriteLine(destination.Name); // 输出:null