自动映射和从Collection或List继承 [英] Automapper and inheritance from Collection or List
问题描述
我正在尝试使用AutoMapper(v5.1.1)映射从列表或集合继承的对象.映射调用不会给我错误,但是输出是一个空列表(尽管类型正确).
I'm trying to use AutoMapper (v5.1.1) to map an object which inherits from a List or Collection. The map call does not give me an error but the output is an empty list (of correct type though).
我可以获得 List< DestinationObject>
或 Collection< DestinationObject>
,但是当具有从 List<继承的自定义类时,它似乎不起作用; T>
或 Collection< T>
.
I can get a List<DestinationObject>
or Collection<DestinationObject>
, but it does not seem to work when having a custom class which enherits from List<T>
or Collection<T>
.
我尝试将第一个地图定义扩展为包括基类( List< T>
),但这给了我StackOverflowException.
I've tried extending the first map definition to include the base class (List<T>
) but that gives me a 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);
}
推荐答案
您只需要将sourceobject映射到destinationobject,AutoMapper将完成其余的工作,有关更多信息,请参见
You just have to map sourceobject to destinationobject, AutoMapper will do rest of the magic, More on this can be found on this link
cfg.CreateMap(typeof(SourceObject), typeof(DestinationObject));
这篇关于自动映射和从Collection或List继承的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!