![](/img/trans.png)
[英]How to preserve the not mapped properties of a collection in a destination object with 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.