As I understand it, OP does not want to clone person2 into a new instance of Person, but asks how to copy the contents of person2 to an existing instance (person1) of Person. There is an overload of the AutoMapper Mapper.Map method that does this for you:
Mapper.CreateMap<Person, Person>(); Mapper.Map<Person, Person>(person2, person1);
Note 1: @alexl answer creates a new instance of Person. If you have other references to the instance pointed to by person1, they will not receive the (supposedly) desired update of the data if you redirect the person1 variable to a new instance.
Note 2:. You should know that the (recursive) copy depth depends on which AutoMapper mappings know at the time of the mapping!
If a member of the Person class talks about the Brain class, and you additionally made Mapper.CreateMap<Brain, Brain>(); before calling the copy Mapper.Map<Person, Person>(person2, person1); , then person1 will retain its current instance of Brain, but this Brain will get the values ββof the member person2. Instance of Brain, You have a deep copy .
But if AutoMapper does not have a Brain-Brain mapping before copying, the person1 member Brain will refer to the same Brain instance as the one person2 link. That is, you will receive a shallow copy .
This applies recursively to all members, so itβs best to make sure that AutoMapper has mappings for the member classes that you want to perform a deep copy and does not have mappings for the member classes that you want to place in a shallow copy.
An alternative to using AutoMapper would be to use a reflection approach . (Note that the code in the link makes a shallow copy!)
"Support for adding an existing object instead of AutoMapper creating the target itself" was added in AutoMapper version 0.2 .
Ulf Γ
kerstedt Feb 28 '13 at 12:10 2013-02-28 12:10
source share