Automapper:忽略条件

是否可以忽略根据源属性的值映射成员?

例如,如果我们有:

public class Car { public int Id { get; set; } public string Code { get; set; } } public class CarViewModel { public int Id { get; set; } public string Code { get; set; } } 

我正在寻找类似的东西

 Mapper.CreateMap() .ForMember(dest => dest.Code, opt => opt.Ignore().If(source => source.Id == 0)) 

到目前为止,我唯一的解决方案是使用两个不同的视图模型,并为每个模型创建不同的映射。

Ignore()function严格适用于您从未映射的成员,因为这些成员也会在配置validation中跳过。 我检查了几个选项,但它看起来不像自定义值解析器就能解决问题。 相反,我将考虑添加条件跳过配置选项,如:

 Mapper.CreateMap() .ForMember(dest => dest.Code, opt => opt.Condition(source => source.Id == 0)) 

我遇到了类似的问题,虽然这将覆盖dest.Code的现有值为null,但它可能有助于作为一个起点:

AutoMapper.Mapper.CreateMap().ForMember(dest => dest.Code,config => config.MapFrom(source => source.Id != 0 ? null : source.Code));