1

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?

Community
  • 1
  • 1
jimjim
  • 2,414
  • 2
  • 26
  • 46

1 Answers1

2

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

Code:

// 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.
Orel Eraki
  • 11,940
  • 3
  • 28
  • 36