我有以下原始类结构:
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,但它没有帮助)。也许我只是写错误的配置。