Automapper: Update property values without creating a new object

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

3 Answers

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.

13

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

3

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

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

You Might Also Like