Automapper:忽略条件

Cas*_*nge 35 c# 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; }
}
Run Code Online (Sandbox Code Playgroud)

我正在寻找类似的东西

Mapper.CreateMap<CarViewModel, Car>()
      .ForMember(dest => dest.Code, 
      opt => opt.Ignore().If(source => source.Id == 0))
Run Code Online (Sandbox Code Playgroud)

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

Jim*_*ard 50

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

Mapper.CreateMap<CarViewModel, Car>()
 .ForMember(dest => dest.Code, opt => opt.Condition(source => source.Id != 0))
Run Code Online (Sandbox Code Playgroud)

  • 我使用最新的生产AutoMapper和Skip方法不存在. (8认同)
  • 这是条件而已. (4认同)

jbe*_*ren 6

我遇到了类似的问题,虽然这会覆盖dest.Codenull 的现有值,但作为一个起点可能会有所帮助:

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