c# - Automapper: Update property values without creating a new object

ID : 10016

viewed : 20

Tags : c#.netautomapperc#

Top 5 Answer for c# - Automapper: Update property values without creating a new object

vote vote

98

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.

vote vote

86

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

vote vote

70

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

vote vote

69

vote vote

52

Top 3 video Explaining c# - Automapper: Update property values without creating a new object

Related QUESTION?