1
我试图使用AutoMapper(v5.1.1)来映射从列表或集合继承的对象。地图调用不会给我一个错误,但输出是一个空列表(虽然是正确的类型)。自动映射器和从集合或列表继承
我可以得到一个List<DestinationObject>
或Collection<DestinationObject>
,但它似乎没有工作时,从List<T>
或Collection<T>
enherits自定义类。
我试过扩展第一个地图定义来包含基类(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);
}
哇,谢谢发现 - 从来没有尝试过只一行: ) 有趣的是,其他代码行都让AutoMapper感到困惑 - 我确定这是需要的,因为我使用了继承,并且在AutoMapper文档中有一个章节。 谢谢! // Mike – Mike