如何使用多继承映射接口?

时间:2016-01-19 23:19:49

标签: c# automapper

我有以下原始类结构:

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);

我预计,我将使用MapToElementDerived作为输出MapTo作为它的Element属性值。但实际上我无法实现它 - Automapper为IMapToElementWritable创建代理。看起来IncludeBase不起作用(我也尝试过Include,但它没有帮助)。也许我只是写错误的配置。

1 个答案:

答案 0 :(得分:0)

看起来Automapper中存在问题。我试图在https://github.com/AutoMapper/AutoMapper/pull/1037

中解决它