使用 AutoMapper 映射派生类型似乎无法预测

Mapping derived types using AutoMapper does not seem to work predictable

我们已经设置了一个具有多个派生类型的基 class

public class Base
{
    public int BaseProperty { get; set; }
}

public class Derived1 : Base { }

public class Derived2 : Derived1
{
    public int Derived2Prop { get; set; }
}

我们还设置了派生的 DTO 模型

public class BaseDto
{
    public int BaseProperty { get; set; }
}

public class Derived1Dto : BaseDto { }

public class Derived2Dto : Derived1Dto
{
    public int Derived2Prop { get; set; }
}

AutoMapper配置映射如下

CreateMap<Base, BaseDto>()
    .Include<Derived1, Derived1Dto>()
    .ReverseMap();

CreateMap<Derived1, Derived1Dto>()
    .Include<Derived2, Derived2Dto>()
    .ReverseMap();

CreateMap<Derived2, Derived2Dto>()
    .ReverseMap();

我写了两个单元测试,第一个按预期工作,但另一个单元测试失败了。对我来说这似乎不正确。

[Test]
public void MappingBaseDtoToDerived()
{
    var mapperConfiguration = new MapperConfiguration(config =>
    {
        config.AddProfile(new BaseMapping());
    });
    var mapper = mapperConfiguration.CreateMapper();

    var dto = new BaseDto { BaseProperty = 1234 };

    var model = new Derived2 { Derived2Prop = 5678 };

    var mapped = mapper.Map(dto, model);

    Assert.AreEqual(5678, model.Derived2Prop);
}

[Test]
public void MappingDerivedDtoToDerived()
{
    var mapperConfiguration = new MapperConfiguration(config =>
    {
        config.AddProfile(new BaseMapping());
    });
    var mapper = mapperConfiguration.CreateMapper();

    var dto = new Derived2Dto { BaseProperty = 1234 };

    var model = new Derived2 { Derived2Prop = 5678 };

    var mapped = mapper.Map(dto, model);

    Assert.AreEqual(5678, model.Derived2Prop);
}

映射派生类型时将使用基本类型的映射。这里不需要Include。你只需要 CreateMap<BaseDto, Base>().