Monday, February 21, 2011

Mapping from different properties based on discriminator value using AutoMapper

I have one very general object that I want to map to a destination type using AutomMapper, but I want to map it to different types depending on the value of a property in the source type. For example, let's say I have:

public class Source
{
    public string Discriminator { get; }
    public string ValueA { get; }
    public string ValueB { get; }
}

public class Target
{
    public string Value { get; set; }
}

And I want to map Source.ValueA to Target.Value if Source.Discriminator == "A" and Source.ValueB to Target.Value if Source.Discriminator == "B".

Is this possible using AutoMapper?

From stackoverflow
  • You can do something like this:

    Mapper.Map<Spurce, Target>().ForMember(x => x.Value, x => x.MapFrom(y => {
        if(y.Discriminator == "A")
            return y.ValueA;
        return y.ValueB;
        });
    
    Karl : I could, but I want to use Automapper's functionality if possible. I reality I have several source fields and several target fields. If I use the method you suggest I will have to add several if/else-statements for each target member which is what I want to avoid.
    Mattias Jakobsson : @Karl, You don't need to hard code it the way I did here. You might just as well use reflection based on your conventions.
    Karl : Ahh, yes, that would work. Thanks!

0 comments:

Post a Comment