简体   繁体   中英

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?

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

public MyDestinationType(MySourceType source)
{
    Mapper.Map<MySourceType, MyDestinationType>(source, this);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM