【问题标题】:Automapper and inheritance from Collection or List自动映射器和从 Collection 或 List 继承
【发布时间】:2016-10-18 01:19:03
【问题描述】:

我正在尝试使用 AutoMapper (v5.1.1) 来映射从列表或集合继承的对象。 map 调用没有给我错误,但输出是一个空列表(尽管类型正确)。

我可以得到一个List<DestinationObject>Collection<DestinationObject>,但是当有一个继承自List<T>Collection<T> 的自定义类时,它似乎不起作用。

我尝试扩展第一个地图定义以包含基类 (List<T>),但这给了我一个 StackOverflowException。

cfg.CreateMap(typeof(SourceCollection), typeof(DestinationCollection)).Include(typeof(List<SourceObject>), typeof(List<DestinationObject>)); 

我在这里错过了什么?

public class SourceCollection : List<SourceObject> {

}

public class DestinationCollection : List<DestinationObject> {

}

public class SourceObject {

    public string Message { get; set; }
}

public class DestinationObject {

  public string Message { get; set; }
}


static void Main(string[] args)
{

    AutoMapper.Mapper.Initialize(cfg =>
    {
        cfg.CreateMap(typeof(SourceCollection), typeof(DestinationCollection)); 
        cfg.CreateMap<List<SourceObject>, List<DestinationObject>>().Include<SourceCollection, DestinationCollection>();
        cfg.CreateMap(typeof(SourceObject), typeof(DestinationObject));
    });

    AutoMapper.Mapper.AssertConfigurationIsValid();

    SourceCollection srcCol = new SourceCollection() { new SourceObject() { Message = "1" }, new SourceObject() { Message = "2" } };
    DestinationCollection dstCol = AutoMapper.Mapper.Map<SourceCollection, DestinationCollection>(srcCol);
}

【问题讨论】:

    标签: c# list inheritance automapper


    【解决方案1】:

    您只需将源对象映射到目标对象,AutoMapper 将完成剩下的工作,更多信息请参见link

    cfg.CreateMap(typeof(SourceObject), typeof(DestinationObject));
    

    【讨论】:

    • 哇,谢谢 - 从来没有尝试过只有那一行 :) 有趣的是,其他行让 AutoMapper 感到困惑 - 我确信它是必需的,因为我使用了继承,并且在 AutoMapper 文档中有专门的一章.谢谢! //迈克
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-20
    • 1970-01-01
    • 1970-01-01
    • 2017-12-07
    • 2011-11-22
    • 2010-11-25
    相关资源
    最近更新 更多