Search code examples
c#automapper

map to derived type of destination in AutoMapper


I want to specify a mapping so that all mappings from "Source" to "Destination" is returned as a derived class of "Destination"

    [Test]
    public void Map_SourceToDestinationAsDerivedType_ReturnsDerivedType()
    {
        // arrange
        AutoMapper.Mapper.CreateMap<Source, Destination>()
            .CreateAs<ActualDestination>() // psedu code
            .ForMember(dst => dst.Transformed, opt => opt.ResolveUsing(src => src.Property));

        var source = new Source{Property = "hi mom" };

        // act
        var destination = AutoMapper.Mapper.Map<Destination>(source);

        // assert
        Assert.That(destination, Is.InstanceOf<ActualDestination>());
    }

    public class Source
    {
        public string Property { get; set; }
    }

    public class Destination
    {

    }

    public class ActualDestination : Destination
    {
        public string Transformed { get; set; }            
    }

Solution

  • This is not directly supported by Automapper

    However the closest what you can get is to define a mapper for the Source, ActualDestination pair

    AutoMapper.Mapper.CreateMap<Source, ActualDestination>() 
        .ForMember(dst => dst.Transformed, opt => opt.ResolveUsing(src => src.Property)); 
    

    And then use the ConstructUsing option in the Source, Destination mapping to do the translation from the Source to the ActualDestination:

    AutoMapper.Mapper.CreateMap<Source, Destination>()
        .ConstructUsing((Source s) => AutoMapper.Mapper.Map<ActualDestination>(s));