简体   繁体   English

自动映射和从集合或列表继承

[英]Automapper and inheritance from Collection or List

I'm trying to use AutoMapper (v5.1.1) to map an object which inherits from a List or Collection. 我正在尝试使用AutoMapper(v5.1.1)来映射从列表或集合继承的对象。 The map call does not give me an error but the output is an empty list (of correct type though). 映射调用不会给我一个错误,但是输出是一个空列表(尽管类型正确)。

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<DestinationObject>Collection<DestinationObject> ,但是当具有从List<T>Collection<T>继承的自定义类时,它似乎不起作用。

I've tried extending the first map definition to include the base class ( List<T> ) but that gives me a StackOverflowException. 我尝试将第一个地图定义扩展为包括基类( List<T> ),但这给了我StackOverflowException。

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

What am I missing here? 我在这里想念什么?

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将完成其余的工作,有关更多信息,请参见此链接。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM