2017-06-27 11 views
1

私はこの質問をまだ見つけられていません。プロパティから1つのオブジェクトを作成し、オートマッペで宛先のコレクションに追加

私は、次のようなオブジェクト構造を持っている:

public class Source 
{ 
    public int SomeId {get;set;} 
    public int NestedIdOne {get;set;} 
    public int NestedIdTwo {get;set;} 
} 

public class Dest 
{ 
    public Dest() 
    { 
     this.Children = new List<Child>(); 
    } 

    public int SomeId {get;set;} 
    public IList<Child> Children {get;set} 
} 

public class Child 
{ 
    public int NestedIdOne {get;set;} 
    public int NestedIdTwo {get;set;} 
} 

だから、アイデアは、ソース・インスタンスautomapperは、子インスタンスを作成し、Dest.Childrenコレクションに追加しますから、ということです。

私はすでに、次のアプローチを使用しています

CreateMap<Source, Dest>().ConstructUsing(MyMethod): 

private Dest MyMethod(Source mySource) 
{ 
    //... build Dest by hand. 
} 

これは正常に動作しますが、私はより多くの「自動」のアプローチがあるかどうかを知りたいです。

私はやって試してみました:

CreateMap<Source, Dest>(); 
CreateMap<Source, Child>(); 

が、これは動作しません。

ありがとうございました。

答えて

0

2つのマップを作成し、親から子マップを呼び出す:

var configuration = new MapperConfiguration(cfg => 
{ 
    cfg.CreateMap<Source, Child>(); 

    cfg.CreateMap<Source, Dest>() 
     .AfterMap((src, dest, ctx) => 
     { 
      dest.Children = new List<Child>(); 

      dest.Children.Add(ctx.Mapper.Map<Child>(src)); 
     }); 
}); 

使用法:

var mapper = configuration.CreateMapper(); 

Dest destination = mapper.Map<Source, Dest>(source); 
+0

すごいです!魅力のように働いた。ありがとう。 –

関連する問題