簡體   English   中英

從屬性創建一個對象,並使用automapper添加到目標集合

[英]Create one object from properties and add to collection of destination with automapper

我很驚訝我還沒有找到這個問題。

我有一個類似於以下的對象結構:

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

因此,想法是從Source實例中,automapper創建一個Child實例並將其添加到Dest.Children集合中。

我已經使用了以下方法:

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

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

這工作正常,但我想知道是否有更“自動”的方法。

我試過這樣做:

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

但這不起作用。

謝謝您的幫助。

創建兩個地圖並從父級調用子地圖:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM