3

I have the following classes.

public class Person {
  public string Name { get; set; }
  public Address Address { get; set; }
}

public class PersonDTO {
  public string Name { get; set; }
  public Address Address { get; set; }
}

I create a standard mapping using

Mapper.CreateMap<Person, PersonDTO>();

Then I'd like to map a Person into an existing PersonDTO hierarchy in that way that the existing Address will be updated instead of reference copied if you know what I mean.

var person = new Person() {
  Name = "Test",
  Address = new Address() {
    Country = "USA",
    City = "New York"
  }
};
var personDTO = new PersonDTO() {
  Name = "Test2",
  Address = new Address() {
    Country = "Canada",
    City = "Ottawa"
  }
};

Mapper.Map(person, personDTO);

I'd like to fulfill the following tests.

Assert.AreNotEqual(person.Address, personDTO.Address);
Assert.AreEqual(person.Address.Country, personDTO.Address.Country);
Assert.AreEqual(person.Address.City, personDTO.Address.City);

1 Answer 1

1

Just create a map between Address and itself like this:

Mapper.CreateMap<Address, Address>();

Please note that the following test:

Assert.AreNotEqual(person.Address, personDTO.Address);

Might not give you want you want if Address defines an Equals method. From what I understand from the question, you want to check for reference equality.

If you are using NUnit, you should use Assert.AreNotSame.

In general you can use object.ReferenceEquals to check for reference equality like this:

bool same_object = object.ReferenceEquals(person.Address, personDTO.Address);
Sign up to request clarification or add additional context in comments.

3 Comments

Thank you, I'm gonna try this. The assertion was just kind of a pseude-codish indication, thanks for the hints though.
Yes this works nicely, thank you. However in the real world I'm using DynamicMap for simplicity and it would be a lot of boilerplate code to define all these self-mappings explicitly. Isn't there any kind of implicit way to make this behavior the default? Or could I create my own method which would try to use CreateMissingTypeMaps for nested mappings too?
There is not a way that I know of. But maybe there is one. Consider posting a question about this.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.