在使用Mapper.ForPath()时,如果原始对象为空,则映射会创建一个新的空对象,而不是映射目标为null。为了解决这个问题,可以使用Mapper.ForPath().MapNullSourceUsing()的方法指定创建目标为null的选项。
例如,假设有以下两个类:
public class Source
{
public int Id { get; set; }
}
public class Destination
{
public int? Id { get; set; }
}
现在我们可以使用以下方式解决这个问题:
var source = new Source { Id = 1 };
Destination destination = null;
Mapper.Initialize(cfg =>
{
cfg.CreateMap()
.ForPath(dest => dest.Id, opt => opt.MapFrom(src => src.Id));
});
destination = Mapper.Map(source, destination, opt => opt
.ForMember(dest => dest.Id, opt => opt.MapFrom(src => src.Id))
.MapNullSourceObjectAsNull(true));
Assert.AreEqual(destination.Id, 1);
在这个例子中,我们通过将MapNullSourceObjectAsNull设置为true来实现映射对象为null的目标。这样就不需要手动创建一个空目标对象,而是可以在映射期间直接返回null。
另外,也可以使用Mapper.ConfigurationProvider.ForAllPropertyMaps()方法,在配置文件级别上指定属性映射选项,这样在整个应用程序中,所有的映射都将使用这个选项。
var config = new MapperConfiguration(cfg =>
{
cfg.ForAllPropertyMaps(pm =>
{
pm.MapNullSourceObjectAsNull = true;
});
cfg.CreateMap()
.ForPath(dest => dest.Id, opt => opt.MapFrom(src => src.Id));
});
var mapper = config.CreateMapper();
这种方法更适合于整个应用程序,以便确保对所有映射都使用相同的选项。