如何将接口映射到多重继承

本文关键字:多重继承 映射 接口 | 更新日期: 2023-09-27 18:31:13

我有以下原始类结构:

public interface IMapFromElement
{
    string Prop { get; }
}
public interface IMapFromElementDerived : IMapFromElement
{
    string Prop2 { get; }
}
public interface IMapFromElement2 : IMapFromElement
{
}
public interface IMapFromElementDerived2 : IMapFromElementDerived, IMapFromElement2
{
}
public abstract class MapFromElement : IMapFromElement2
{
    public string Prop { get; set; }
}

public class MapFromElementDerived : MapFromElement, IMapFromElementDerived2
{
    public string Prop2 { get; set; }
}

我正在尝试将它们映射到:

public class MapTo
{
    public IMapToElementWritable Element { get; set; }
}
public interface IMapToElementWritable : IMapFromElement
{
    new string Prop { get; set; }
}
public interface IMapToElementWritableDerived : IMapFromElementDerived, IMapToElementWritable
{
    new string Prop2 { get; set; }
}
public abstract class MapToElement : IMapToElementWritable
{
    public string Prop { get; set; }
}
public class MapToElementDerived : MapToElement, IMapToElementWritableDerived
{
    public string Prop2 { get; set; }
}

我尝试将它们映射为:

var from = new MapFrom
{
    Element = new MapFromElementDerived {Prop = "qwerty", Prop2 = "asdf"}
};
Mapper.Initialize(
    cfg =>
    {
        cfg.CreateMap<IMapFrom, MapTo>();
        cfg.CreateMap<IMapFromElement, IMapToElementWritable>();
        cfg.CreateMap<IMapFromElementDerived, IMapToElementWritableDerived>()
            .IncludeBase<IMapFromElement, IMapToElementWritable>()
            .ConstructUsing((ResolutionContext item) => new MapToElementDerived());
        cfg.Seal();
    });
Mapper.AssertConfigurationIsValid();
var result = Mapper.Map<MapTo>(from);

我期望,我将输出MapTo与MapToElementDerived 作为它的元素属性值。但实际上我无法实现它 - 自动映射器为IMapToElementWritable创建代理。看起来 IncludeBase 不起作用(我也尝试过使用 Include,但它没有帮助)。也许我只是写了错误的配置。

如何将接口映射到多重继承

看起来自动映射器中存在问题。我试图在 https://github.com/AutoMapper/AutoMapper/pull/1037 中解决它