Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AutoMapper - Conditional Mapping

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.

like image 715
pdalbe01 Avatar asked Dec 16 '22 14:12

pdalbe01


2 Answers

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")
);
like image 60
Darin Dimitrov Avatar answered Dec 19 '22 05:12

Darin Dimitrov


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
                 }
            });
like image 41
Dan Avatar answered Dec 19 '22 04:12

Dan