Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to map to "this" with AutoMapper in constructor

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?

like image 317
g.pickardou Avatar asked Apr 23 '15 13:04

g.pickardou


1 Answers

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

public MyDestinationType(MySourceType source)
{
    Mapper.Map<MySourceType, MyDestinationType>(source, this);
}
like image 103
Alex Avatar answered Sep 21 '22 16:09

Alex