繁体   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