自动映射 - 更新现有实例

时间:2018-05-12 18:39:13

标签: c# automapper

我有这些课程:

public class SourceA 
{
  public double SourceAProp { get; set; }
}

public class SourceB
{
  public double SourceBProp { get; set; }
}

public class Dest
{
  public double SourceAProp { get; set; }
  public double SourceBProp { get; set; }
} 

我试过:

var config = new MapperConfiguration(cfg => cfg.CreateMap<SourceA, Dest>());
var mapper = config.CreateMapper();            
var dest = mapper.Map<SourceA, Dest>(sourceA.Value);

config = new MapperConfiguration(cfg => cfg.CreateMap<SourceB, Dest>());
mapper = config.CreateMapper();            
dest = mapper.Map<SourceB, Dest>(sourceB.Value);

但我认为Map会在每次执行时创建实例。

如何使用AutoMapper创建包含DestSourceA个实例值的单个SourceB实例(或在首次执行后更新创建的实例)?

1 个答案:

答案 0 :(得分:1)

Map<...>()方法有一个重载,您可以在其中提供目标对象。所以它基本上是

Dest dest = new Dest();
mapper.Map<SourceA, Dest>(sourceA.Value, dest);
//...
mapper.Map<SourceB, Dest>(sourceB.Value, dest);