Automapper: Ignore on condition of

2019-01-08 01:23发布

Is it possible to ignore mapping a member depending on the value of a source property?

For example if we have:

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; }
}

I'm looking for something like

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

So far the only solution I have is too use two different view models and create different mappings for each one.

标签: c# AutoMapper
2条回答
在下西门庆
2楼-- · 2019-01-08 02:04

I ran into a similar issue, and while this will overwrite the existing value for dest.Code with null, it might be helpful as a starting point:

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

查看更多
等我变得足够好
3楼-- · 2019-01-08 02:05

The Ignore() feature is strictly for members you never map, as these members are also skipped in configuration validation. I checked a couple of options, but it doesn't look like things like a custom value resolver will do the trick. Instead, I'll look at adding a conditional Skip configuration option, like:

Mapper.CreateMap<CarViewModel, Car>()
 .ForMember(dest => dest.Code, opt => opt.Condition(source => source.Id == 0))
查看更多
登录 后发表回答