Automapper: Update property values without creating a new object – Dev

The best answers to the question “Automapper: Update property values without creating a new object” in the category Dev.

QUESTION:

How can I use automapper to update the properties values of another object without creating a new one?

ANSWER:

To make this work you have to CreateMap for types of source and destination even they are same type.
That means if you want to
Mapper.Map<User, User>(user1, user2);
You need to create map like this
Mapper.Create<User, User>()

ANSWER:

Use the overload that takes the existing destination:

Mapper.Map<Source, Destination>(source, destination);

Yes, it returns the destination object, but that’s just for some other obscure scenarios. It’s the same object.

ANSWER:

If you wish to use an instance method of IMapper, rather than the static method used in the accepted answer, you can do the following (tested in AutoMapper 6.2.2)

IMapper _mapper;
var config = new MapperConfiguration(cfg =>
{
    cfg.CreateMap<Source, Destination>();
});
_mapper = config.CreateMapper();

Source src = new Source
{
//initialize properties
}

Destination dest = new dest
{
//initialize properties
}
_mapper.Map(src, dest);

dest will now be updated with all the property values from src that it shared. The values of its unique properties will remain the same.

Here’s the relevant source code