在使用AutoMapper时,有时候需要忽略源对象中的某些成员,以保证映射的正确性。而AutoMapper提供的.Ignore()方法可以达到这个效果。但是有时候会遇到这种情况:使用了.Ignore()方法,但是映射后的目标对象依然有值。这是因为AutoMapper默认的行为是覆盖目标对象中的值,而不是删除目标对象中的成员。
要解决这个问题,可以使用.Condition()方法结合.Lambda重写.AutoMapper的默认行为。例如,以下代码实现了只映射源对象中非空的成员:
Mapper.Initialize(cfg =>
{
cfg.CreateMap()
.ForMember(dest => dest.SomeProperty, opt => opt.Condition(src => src.SomeProperty != null))
.ForMember(dest => dest.AnotherProperty, opt => opt.Condition(src => src.AnotherProperty != null))
.ForMember(dest => dest.YetAnotherProperty, opt => opt.Condition(src => src.YetAnotherProperty != null));
});
这里使用了.Lambda来创建Lambda表达式,以便能够在.AutoMapper中使用条件表达式。现在,只有在源对象中该成员非空的情况下,目标对象才会映射该成员。