AutoMapper - conditional mapping

I looked around and could not find the answer to my question. What I want to do is a conditional map of the target object (not a field / property, object). In other words, something like this:

public class Source { public int Id {get; set;} public string Flag {get; set;} } public class Destination { public int Id {get; set;} } var sources = new List<Source> { new Source{Flag = "V", Id = 1}, new Source{Flag = "B", Id = 2} }; var destinations = Mapper.Map<List<Source>, List<Destination>>(sources); destinations.Count.ShouldEqual(1); destinations[0].Id.ShouldEqual(2); 

Does anyone know how to set up type matching? I am looking for something like:

 Mapper.CreateMap<Source, Destination>() .SkipIf(src => src.Flag != "B"); 

I just don't see anything in the configuration settings that seem to support this. Any help is appreciated! Thanks in advance.

+4
source share
2 answers

AFAIK there is currently nothing built-in allowing you to achieve this. You could do the following though:

 var destinations = Mapper.Map<List<Source>, List<Destination>>( sources.Where(source => source.Flag == "B") ); 
+6
source

This is not as good as you end up doing the mapping yourself .... but its normal for exceptional cases and allows the display logic to contain within itself.

  config.CreateMap<Source, Destination>() .AfterMap((source, dest) => { if (source.Flag == "B") { //do stuff } }); 
+4
source

All Articles