【发布时间】: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