Arjang Arjang -4 years ago 172
C# Question

Automapper, cloning objects between Same Complex Class or Their Homeomorphic Equivalant class

In this question, cloning of simple class is answered.

My Question is

  1. Would the same approach work for classes with complex properties? or the entire class property hierarchies needs to be mapped?

  2. Is there an easy way copy two complex classes with exactly same structure (homeomorphic) with AutoMapper?

Answer Source

Yes, You can use AutoMapper for all of those requests.

  1. Yes the same approach will work for Complex types as well, As long as you creating a map from there as well.

  2. AutoMapper will do that for you.

Link for .NETFiddle


// Creating poco instance
var personDTO = new PersonDTO
    FirstName = "Jon",
    LastName = "Smith",
    Address = new AddressDTO
        City = "New York City",
        State = "NY",
        Street = "12 Main ST",
        ZipCode = "32211"

// Create a mapping scheme
AutoMapper.Mapper.CreateMap<AddressDTO, Address>();
AutoMapper.Mapper.CreateMap<PersonDTO, Person>();
AutoMapper.Mapper.CreateMap<AddressDTO, Address>().ReverseMap();
AutoMapper.Mapper.CreateMap<PersonDTO, Person>().ReverseMap();

// Creating the destination type
var person = AutoMapper.Mapper.Map<PersonDTO, Person>(personDTO);
Console.WriteLine("I'm {0} {1} and i'm from {2} state.", person.FirstName, person.LastName, person.Address.State);
// Output: I'm Jon Smith and i'm from NY state.
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download