映射到AutoMapper中的派生目标类型

时间:2014-02-12 12:04:53

标签: automapper

我想指定一个映射,以便所有映射来自" Source"到目的地"作为" 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; }            
    }

1 个答案:

答案 0 :(得分:3)

Automapper

不直接支持

然而,您可以获得的最接近的是为Source, ActualDestination

定义一个映射器
AutoMapper.Mapper.CreateMap<Source, ActualDestination>() 
    .ForMember(dst => dst.Transformed, opt => opt.ResolveUsing(src => src.Property)); 

然后使用ConstructUsing映射中的Source, Destination选项进行从SourceActualDestination的翻译:

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