繁体   English   中英

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

暂无
暂无

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

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