2016-09-29 55 views
0

我正在嘗試映射對象,但實際上效果並不好。從源對象映射到目標對象及其子對象集合

我有結構的源對象:

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 
} 

有2型和3型之間type1和對象C和映射之間的映射。然而,type3子列表總是空的,因爲需要在對象prod物種和子集(它是集合)之間有一個映射。 如何將值從源映射到目標子對象集合。

回答

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