AutoMapper是否能够基于现有地图自动解析类型

时间:2010-05-05 16:39:10

标签: automapper

我有以下代码:

[SetUp]
public void SetMeUp()
{
     Mapper.CreateMap<SourceObject, DestinationObject>();
}

[Test]
public void Testing()
{
     var source = new SourceObject {Id = 123};
     var destination1 = Mapper.Map<SourceObject, DestinationObject>(source);
     var destination2 = Mapper.Map<ObjectBase, ObjectBase>(source);

     //Works
     Assert.That(destination1.Id == source.Id);

     //Fails, gives the same object back
     Assert.That(destination2 is DestinationObject);
}

public class ObjectBase
{
     public int Id { get; set; }
}

public class SourceObject : ObjectBase { }
public class DestinationObject : ObjectBase { }

基本上,我希望AutoMapper根据AutoMapper中设置的现有地图自动将目标类型解析为“DestinationObject”。有没有办法实现这个目标?

1 个答案:

答案 0 :(得分:1)

您可以使用最新版本(1.1)尝试以下映射:

Mapper.CreateMap<ObjectBase,ObjectBase>()
  .Include<SourceObject, DestinationObject>();

Mapper.CreateMap<SourceObject, DestinationObject>();