7

I have a source type which have properties and a destination type which have exactly the same properties.

After I configure one simple mapping for AutoMapper like:

Mapper.CreateMap<MySourceType, MyDestinationType>();

I would like to have a constructor of MyDestinationType which have a MySourceType parameter, then automatically initialize properties of the type under creation with the source like this:

public MyDestinationType(MySourceType source)
{
    // Now here I am do not know what to write.
}

The only workaround I found is create a static factory method for

public static MyDestinationType Create(MySourceType source)
{
     return Mapper.Map<MyDestinationType>(source);
}

Is there any way to not to have this static ugliness?

g.pickardou
  • 32,346
  • 36
  • 123
  • 268
  • Why build a constructor? You want to be able to call `MyDestinationType destinationobj = new MyDestinationType(sourceobj);` but this would do the same as simply calling `MyDestinationType destinationobj = Mapper.Map(sourceobj);` If you really need a seperate constructor you could TRY `this = Mapper.Map(source);` but I'm not 100% sure if you can do a direct assignment to `this`. Edit: I tested it and you can't assign to `this`. – Nils O Apr 23 '15 at 13:43

2 Answers2

10

Although I personally find it ugly, what you can do is the following:

public MyDestinationType(MySourceType source)
{
    Mapper.Map<MySourceType, MyDestinationType>(source, this);
}
Alex
  • 13,024
  • 33
  • 62
0

I achieved this using:

public MyDestinationType(MySourceType source)
{
    var mapperConfiguration = new MapperConfiguration(cfg =>
    {
        cfg.CreateMap<MySourceType, MyDestinationType>();
    });

    var mapper = mapperConfiguration.CreateMapper();

    mapper.Map(source, this);
}
tno2007
  • 1,993
  • 25
  • 16