0

I'd like to merge two objects using AutoMapper (see test below). I've tried a bunch of things but it always copies both properties from the target or the source.

How can I pass the Test below?

public class Person
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
}

[Test]
public void Merge_people()
{
    var source = new Person() { LastName = "Smith" };
    var target = new Person() { FirstName = "John" };

    Mapper.CreateMap<Person, Person>();
    Mapper.Map(source, target);

    Assert.That(target.FirstName == "John");
    Assert.That(target.LastName == "Smith");
}
Matt Fitzmaurice
  • 1,319
  • 4
  • 19
  • 40

2 Answers2

4

Using properly defined condition you can manage what you need:

 Mapper.CreateMap<Person, Person>()
       .ForAllMembers(o => o.Condition((source, destination, member) => member != null));

It will map only members that are different than null. I am using AutoMapper 6.1.1, but I believe it should work for older versions as well.

Marta
  • 326
  • 4
  • 11
1

I believe Automapper doesn't yet have that kind of functionality. See link here

Community
  • 1
  • 1
jtabuloc
  • 2,479
  • 2
  • 17
  • 33