Automapper: Update property values without creating a new object

C#.NetAutomapper

C# Problem Overview


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

C# Solutions


Solution 1 - C#

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.

Solution 2 - C#

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

Solution 3 - C#

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionryudiceView Question on Stackoverflow
Solution 1 - C#Jimmy BogardView Answer on Stackoverflow
Solution 2 - C#Flux XuView Answer on Stackoverflow
Solution 3 - C#BobbyAView Answer on Stackoverflow