【问题标题】:Automapper - Map list of objects to single complex type with nested objectsAutomapper - 将对象列表映射到具有嵌套对象的单个复杂类型
【发布时间】:2020-01-07 08:41:40
【问题描述】:

我正在使用 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; }
}

谢谢!

【问题讨论】:

  • 为什么?你得到SourceBase 的列表?为什么不将其映射到DestBase 的列表?
  • 因为我们想让前端视图模型更简单

标签: c# asp.net-core .net-core automapper


【解决方案1】:

基本上我已经用 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>();

【讨论】:

    猜你喜欢
    • 2020-04-03
    • 1970-01-01
    • 2019-04-26
    • 2012-10-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多