使用派生类型从基本列表映射到另一个基本列表

时间:2016-02-03 23:15:12

标签: inheritance automapper

我试图映射以下内容。

public abstract class AnimalBLO { }

public abstract class AnimalDLO { }

public class HumanBLO : AnimalBLO { }

public class HumanDLO : AnimalDLO { }

public class LionBLO : AnimalBLO { }

public class LionDLO : AnimalDLO { }

internal class Program
{
    private static void Main(string[] args)
    {
        Mapper.CreateMap<HumanDLO, HumanBLO>();
        Mapper.CreateMap<LionDLO, LionBLO>();

        var dlos = new List<AnimalDLO>()
        {
            new HumanDLO(),
            new LionDLO()
        };

        var result = Mapper.Map<List<AnimalBLO>>(dlos);

    }
}

列表的基本类型是AnimalBLO,但它们被映射为派生类型。有没有办法在不丢弃所有对象的情况下执行此操作,然后将它们组合在一起?

我认为这段代码可行:

        Mapper.CreateMap<AnimalDLO, AnimalBLO>()
            .Include<HumanDLO, HumanBLO>()
            .Include<LionDLO, LionBLO>();

        Mapper.CreateMap<HumanDLO, HumanBLO>();
        Mapper.CreateMap<LionDLO, LionBLO>();

但是,抛出以下异常消息:

  

{&#34;无法创建抽象类的实例。&#34;}

2 个答案:

答案 0 :(得分:1)

AutoMapper的Mapping inheritance功能完全按照您的描述运行。我已经在类中添加了Tag属性来验证调用了哪个映射:

public abstract class AnimalBLO
{
    public string Tag { get; set; }
}

这是成功的测试:

[SetUp]
public void SetUp()
{
    Mapper.Initialize(cfg => {
        cfg.CreateMap<AnimalDLO, AnimalBLO>()
              .Include<HumanDLO, HumanBLO>()
              .Include<LionDLO, LionBLO>();
        cfg.CreateMap<HumanDLO, HumanBLO>().AfterMap((src, dest) => dest.Tag = "mapped as Human");
        cfg.CreateMap<LionDLO, LionBLO>();
    });
}

[Test]
public void Test()
{
    var dlos = new List<AnimalDLO>
    {
        new HumanDLO(),
        new LionDLO()
    };

    var result = Mapper.Map<List<AnimalBLO>>(dlos);
    var human = result.First();

    Assert.IsInstanceOf(typeof(HumanBLO), human);
    Assert.AreEqual("mapped as Human", human.Tag);
} 

答案 1 :(得分:0)

4.2版(可能是5.X)解决方案如下:

var config = new MapperConfiguration(cfg =>
{

    cfg.CreateMap<AnimalDLO, AnimalBLO>()
        .Include<HumanDLO, HumanBLO>()
        .Include<LionDLO, LionBLO>();

    cfg.CreateMap<HumanDLO, HumanBLO>();
    cfg.CreateMap<LionDLO, LionBLO>();
});

var dlos = new List<AnimalDLO>
{
    new LionDLO(),
    new HumanDLO(),
};

var result = config.CreateMapper().Map<List<AnimalBLO>>(dlos);