Automapper and inheritance from Collection or List

只谈情不闲聊 提交于 2021-02-19 07:45:07

问题


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).

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>.

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>)); 

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);
}

回答1:


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));


来源:https://stackoverflow.com/questions/39971563/automapper-and-inheritance-from-collection-or-list

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!