自动装配器和从集合或列表继承

本文关键字:集合 列表 继承 | 更新日期: 2023-09-27 18:12:23

我试图使用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);
}

自动装配器和从集合或列表继承

您只需要将源对象映射到目的地对象,AutoMapper将完成其余的魔法,更多信息可以在此链接中找到

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