Copy Object to Object (With Automapper )

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

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.

Deep cloning an object with Automapper, can't exclude Id property on objects in a ListabstractBaseClass property

I solved it the following way:

First, I updated to Automapper 4.1.1. Then:

        Mapper.Initialize(cfg =>
{
cfg.CreateMap<Question, Question>()
.Include<TextBoxQuestion, TextBoxQuestion>()
// Supposedly inheritance mapping?
.ForMember(rec => rec.Id, opt => opt.Ignore());

cfg.CreateMap<TextBoxQuestion, TextBoxQuestion>()
// But either I don't understand inheritance mapping or it doesn't work, soI have to do that too
.ForMember(rec => rec.Id, opt => opt.Ignore());

cfg.CreateMap<SomeCompositeClass, SomeCompositeClass>()
.ForMember(rec => rec.Id, opt => opt.Ignore())
}

...
Mapper.Map(source, destination);

and it works...

So I think what I was mostly missing was the .Include part, which tells Automapper to look for the most derived class.

Copy values from object1 to object2 using AutoMapper

To Map from PersonDto to Person you need to configure the attribute to allow reverse configuration.

Change the attribute to look like this:

[MapsTo(typeof(Person), ReverseMap = true)]

this will allow to call AutoMapper for PersonDto -> Person, to see more you can check the README of the project here.

How to deep clone objects containing an IList property using AutoMapper

here is one solution with the ValueInjecter

        var clone = new MainData();

clone.InjectFrom(mainData);//mainData is your source

mainData.Details.AsParallel.ForAll(detail =>
{
var dc = new Detail();
dc.InjectFrom(detail);
clone.AddDetail(dc);
});

the properties that have private setters are not going to be set, (looks reasonable)

good luck ;)

EDIT:
I did a better solution look here



Related Topics



Leave a reply



Submit