views:

275

answers:

1

I would like to define a mapping (or even a TypeConverter/Resolver) for the following classes: Destination:

   public class Destination
    {
        public DestinationEnum EnumProperty { get; set; }

        public Destination()
        {
            EnumProperty = DestinationEnum.undefined;
        }
    }

    public enum DestinationEnum
    {
        oneValue,
        anotherValue, 
        undefined
    }

Source:

    public enum SourceEnum
    { 
        fu,
        ba
    }

    public enum AnotherSourceEnum
    { 
        first,
        second, 
        third
    }

    public class Source
    {
        public SourceEnum SourceEnumVal { get; set; }
    }

    public class ConcreteSource : Source
    {
        public AnotherSourceEnum ConcreteSourceEnumVal { get; set; }
    }

What would the AutoMapper Mapping look like, if I want to specify a destination value of the DestinationEnum in the Destination class depending on the concrete Source Type? E.g.

  • if the mapper maps from class "Source" to "Destination", the Destination.EnumProperty should be set to "undefined" if Source.SourceEnumVal == fu
  • if the mapper maps from class "source" to "Destination", the Destination.EnumProperty should be set to "oneValue" if Source.SourceEnumVal == "ba"
  • if the mapper maps from class "ConcreteSource" to "Destination", the Destination.EnumProperty should be set to "oneValue" if ConcreteSource.ConcreteSourceEnumVal == "second"
  • if the the mapper maps from class "ConcreteSource" to "Destination", the Destination.EnumProperty should be set to "undefined" if ConcreteSource.ConcreteSourceEnumVal != "second"
+3  A: 

You would create two maps:

Mapper.CreateMap<Source, Destination>();
Mapper.CreateMap<ConcreteSource, Destination>();

Then do a custom resolver for each map:

Mapper.CreateMap<Source, Destination>()
    .ForMember(dest => dest.EnumProperty, opt => opt.ResolveUsing<FirstResolver>());

Your second ConcreteSource map would use a different resolver:

Mapper.CreateMap<ConcreteSource, Destination>()
    .ForMember(dest => dest.EnumProperty, opt => opt.ResolveUsing<SecondResolver>());

AutoMapper chooses the mapping to use based on both the source and destination type, so the correct resolver will be chosen no matter which of the source types you use.

Jimmy Bogard