Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Automapper - update existing instance

Tags:

c#

automapper

I have these classes:

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

I've tried to:

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

But I think Map creates instance on each execution.

How can I use AutoMapper to create a single Dest instance with both SourceA and SourceB instances values (or updating the created instance after first execution) ?

like image 800
ohadinho Avatar asked Jul 30 '26 01:07

ohadinho


1 Answers

The Map<...>() method has an overload where you can supply the destination object. So it's basically

Dest dest = new Dest();
mapper.Map<SourceA, Dest>(sourceA.Value, dest);
//...
mapper.Map<SourceB, Dest>(sourceB.Value, dest);
like image 200
Progman Avatar answered Jul 31 '26 13:07

Progman