2017-09-15 56 views
0

来源这些是Source类。 Prop2是一种​​复杂的类型,我希望在我的目的地中变平。Automapper-如何将复杂的对象表单源映射到目标中的扁平属性?

public class Source1 
{ 
    public string Prop1 { get; set; } 
    public ICollection<Source2> Prop2 { get; set; } 
} 

public class Source2 
{ 
    public string Prop3 { get; set; } 
    public decimal Prop4 { get; set; } 
    public bool Prop5 { get; set; } 
} 

目标这是目标类

public class Destination 
{ 
    public string Prop1 { get; set; } 
    public string Prop3 { get; set; } 
    public decimal Prop4 { get; set; } 
    public bool Prop5 { get; set; } 
} 

预期结果应该是所有属性的目的地类

{ 
[ 
    prop1: "abc1", 
    prop3: efg1, 
    prop4: 123.4, 
    prop5: true 
], 

[ 
    prop1: "abc2", 
    prop3: efg2, 
    prop4: 123.5, 
    prop5: false 
], 

[ 
    prop1: "abc3", 
    prop3: efg3, 
    prop4: 123.6, 
    prop5: true 
], 

[ 
    prop1: "abc4", 
    prop3: efg4, 
    prop4: 123.7, 
    prop5: false 
], 

........ 
........ 
........ 

} 

回答

0
Mapper.Initialize(cfg => 
{ 
    cfg.CreateMap<Source2,Destination>().ForMember(d=>d.Prop1, o=>o.ResolveUsing((s,_,__,context)=>context.Items["Prop1"])); 
}); 
Mapper.AssertConfigurationIsValid(); 

var source = new Source1 { Prop1="1", Prop2 = new List<Source2> { new Source2 {}, new Source2 {}, new Source2 {} }}; 
Mapper.Map<IEnumerable<Destination>>(source.Prop2, opts=>opts.Items["Prop1"]=source.Prop1).Dump(); 
+0

真棒集合!我会试试看。 – kPank

相关问题