How to tell AutoMapper to use "pass by reference?"

By default, automapper creates a new object based on the destination type:

public void Doit( Person personMissingStuff ) { PersonTemplate template = _personDao.GetPersonTemplate(1); Mapper.CreateMap<PersonTemplate, Person>(); Person basePerson = Mapper.Map<Person>( template ); Mapper.CreateMap<Person, Person>(); Person completePerson = Mapper.Map<Person, Person>( basePerson, personMissingStuff ); ... } 

Instead of getting completePerson I again get a basePerson . How do I tell AutoMapper to start matching by reference instead of value?

+4
source share
2 answers

Mapper.Map(source, dest) actually returns the destination object, in your case it will be personMissingStuff .

With that said, assuming that you only want to fill in the null properties in the receiver, you need to properly configure the display, not the map in which the destination property matters.

The following example does just that for class properties. For value properties, you probably need to do some additional configuration. The example uses NUnit and SharpTestsEx:

 [TestFixture] public class LoadIntoInstance { public class Template { public string Name { get; set; } } public class Person { public string Name { get; set; } public string OtherData { get; set; } } [Test] public void Should_load_into_instance() { Mapper.CreateMap<Template, Person>() .ForMember(d=>d.OtherData, opt=>opt.Ignore()); Mapper.CreateMap<Person, Person>() .ForAllMembers(opt=>opt.Condition(ctx=>ctx.DestinationValue==null)); Mapper.AssertConfigurationIsValid(); var template = new Template {Name = "template"}; var basePerson = Mapper.Map<Person>(template); var noNamePerson = new Person {OtherData = "other"}; var result = Mapper.Map(basePerson, noNamePerson); result.Should().Be.SameInstanceAs(noNamePerson); result.Satisfy(r => r.Name == "template" && r.OtherData == "other"); } } 
0
source

Just use traditional shallow cloning ...

 Person completePerson = basePerson.MemberwiseClone(); 

This should contain reference types and clone value types.

MSDN Link

-1
source

Source: https://habr.com/ru/post/1483441/


All Articles