Automapper: Update property values without creating a new object
C#.NetAutomapperC# 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.