I've looked around and couldn't quite find the answer to my question. What I'm looking to do is conditional map the destination object (not 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 configure the type mapping? I'm looking for something like:
Mapper.CreateMap<Source, Destination>()
.SkipIf(src => src.Flag != "B");
I just don't see anything in the configuration options that seems to support this. Any help would be much appreciated! Thanks in advance.
AFAIK currently there is 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")
);
This is not great as you effectively end up doing the mapping yourself....but its ok for exceptional cases and allows the mapping logic to be contained internally....
config.CreateMap<Source, Destination>()
.AfterMap((source, dest) =>
{
if (source.Flag == "B")
{
//do stuff
}
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With