我想指定一个映射,以便所有映射来自" 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; }
}
答案 0 :(得分:3)
Automapper
不直接支持然而,您可以获得的最接近的是为Source, ActualDestination
对
AutoMapper.Mapper.CreateMap<Source, ActualDestination>()
.ForMember(dst => dst.Transformed, opt => opt.ResolveUsing(src => src.Property));
然后使用ConstructUsing
映射中的Source, Destination
选项进行从Source
到ActualDestination
的翻译:
AutoMapper.Mapper.CreateMap<Source, Destination>()
.ConstructUsing((Source s) => AutoMapper.Mapper.Map<ActualDestination>(s));