Automapper ignores property ignore

I would like to ignore some properties when displaying deep (i.e. levels> 1) object models.

The following test works fine:

class Foo { public string Text { get; set; } } class Bar { public string Text { get; set; } } Mapper.CreateMap<Foo, Bar>() .ForMember(x => x.Text, opts => opts.Ignore()); var foo = new Foo { Text = "foo" }; var bar = new Bar { Text = "bar" }; Mapper.Map(foo, bar); Assert.AreEqual("bar", bar.Text); 

However, when I try to do the same mapping, but have the Foo and Bar properties as properties of the parent class, the following test fails:

 class ParentFoo { public Foo Child { get; set; } } class ParentBar { public Bar Child { get; set; } } Mapper.CreateMap<ParentFoo, ParentBar>(); Mapper.CreateMap<Foo, Bar>() .ForMember(x => x.Text, opts => opts.Ignore()); var parentFoo = new ParentFoo { Child = new Foo { Text = "foo" } }; var parentBar = new ParentBar { Child = new Bar { Text = "bar" } }; Mapper.Map(parentFoo, parentBar); Assert.AreEqual("bar", parentBar.Child.Text); 

Instead of ignoring the text of the Child class (that is, leaving it as "bar"), automapper sets the value to null. What am I doing wrong with my display configuration?

+7
source share
1 answer

There are two ways Automapper can match. The first way is to simply give Automapper the source object, and it will create a new destination object and populate everything for you. So most applications use Automapper. However, the second way is to provide it with both the source and the existing destination, and Automapper will update the existing destination using your mappings.

In the first example, you give it the existing destination value, so Automapper will use this. In the second example, Automapper is about to perform a mapping for ParentFoo and ParentBar, but when it reaches the Child, it is about to create a new Child and then perform the mapping (this is the default behavior). As a result, the Text property is null. If you want to use an existing child, you need to configure Automapper for this with UseDestinationValue:

 Mapper.CreateMap<ParentFoo, ParentBar>() .ForMember(b => b.Child, o => o.UseDestinationValue()); 

This makes your test pass (if you get rid of the first place when setting parentBar.Child.Text!).

+9
source

All Articles