Automapper - 将对象列表映射到具有嵌套对象的单一复杂类型

Automapper - Map list of objects to single complex type with nested objects

我正在使用 Automapper,我需要将对象列表映射到单个复杂类型,其中有很多嵌套对象,但我找不到正确的方法。当然我还有很多更具体的对象,但我只是简化了我的情况。

来源:

public abstract class SourceBase 
{
    public int? Value { get; set; }
}

public class Source1 : SourceBase
{
}

public class Source2 : SourceBase
{
}

目的地:

public abstract class DestBase 
{
    public int? Value { get; set; }
}

public class Dest1 : DestBase
{
}

public class Dest2 : DestBase
{
}

我收到来自服务的回复:

public List<SourceBase> Foo { get; set; }

我想把它映射到这个对象中:

public class DestObj 
{
    public Dest1 Dest1Obj { get; set; }
    public Dest2 Dest2Obj { get; set; }
}

谢谢!

基本上我已经用 Linq 编写了自定义映射器。

CreateMap<List<SourceBase>, DestObj>()
    .ForMember(dest => dest.Dest1Obj, opt => opt.MapFrom(src => src.Single(x => x.GetType() == typeof(Source1))))
    .ForMember(dest => dest.Dest2Obj, opt => opt.MapFrom(src => src.Single(x => x.GetType() == typeof(Source2))));

CreateMap<Source1, Dest1>();
CreateMap<Source2, Dest2>();