Automapper: Ignore on condition of

Castrohenge picture Castrohenge · Mar 16, 2010 · Viewed 22.2k times · Source

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.

Answer

Jimmy Bogard picture Jimmy Bogard · Mar 16, 2010

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.

Use the Condition() feature to map the member when the condition is true:

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