How can I use automapper to update the properties values of another object without creating a new one?
4 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.
15 Comments
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>()
4 Comments
mapper.Map(source, destination) wasn't updating the destination object. My understanding was that AutoMapper would automatically create an implicit mapping between objects of the same type. I read this answer and tried adding an explicit mapping from the type to itself (similar to the mapping of User to User in this answer) and now it works.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.
Comments
There's two things to note here. First, we don't have to specify the type to map to for the generic Map call. This is because, now, we're passing the destination object instance, so the destination type can be determined by the type of that object. Second, we're not storing the result of this call in a variable. This is because the destination object is mapped to in place and we're not creating any new instances.
AutoMapper.Mapper.Map(sourceObject, destinationObject);