从源对象映射到目标对象及其子对象集合

时间:2016-09-29 19:55:35

标签: json automapper

我正在尝试绘制对象,但它并没有真正起作用。

我有源对象结构:

Object Prod
{
     object<type1> Attribute (this object has fields field A,field B etc);
     List<type2> Species;
}

我的目标对象:

Object C
{
    field A,
    field B
    List<type3> subs
}

type1和object C之间存在映射,type2和type3之间存在映射。但是,type3子列表总是空的,因为在对象prod物种和subs(它是集合)之间需要有一个映射。 如何将值从源子对象集合映射到目标子对象集合。

1 个答案:

答案 0 :(得分:0)

public class Prod
{
    public Type1 Attribute;
    public List<Type2> Species;
}

public class C
{
    public int A;
    public string B;
    public List<Type3> Subs;
}

public class Type1
{
    public int A;
    public string B;
}

public class Type2
{
    public int C;
}

public class Type3
{
    public int D { get; set; }
}

Mapper.CreateMap<Prod, C>()
    .ForMember(d => d.A, o => o.MapFrom(s => s.Attribute.A))
    .ForMember(d => d.B, o => o.MapFrom(s => s.Attribute.B))
    .ForMember(d => d.Subs, o => o.MapFrom(s => s.Species));

Mapper.CreateMap<Type2, Type3>().ForMember(d => d.D, o => o.MapFrom(s => s.C));

var prod = new Prod
{
    Attribute = new Type1 { A = 1, B = "1" },
    Species = new List<Type2> { new Type2 { C = 2 }, new Type2 { C = 3 } }
};

var c = Mapper.Map<C>(prod);