I've looked around and couldn't quite find the answer to my开发者_如何学Go 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
}
});
精彩评论