1

I am using Automapper to patch an object onto itself.

I want to ignore null values from the source object when doing the mapping. This works for collections by using AllowNullCollections = true;. When I have a destination object that contains a dictionary with some elements and I try to map a source object that contains a null dictionary, I expect the null dictionary to be ignored because I am ignoring null collections.

But on my destination object, the Dictionary wind up empty. Is this the expected behavior for Dictionaries?

This is my profile

AllowNullCollections = true;

CreateMap<T, T>()
.ForAllOtherMembers(o => o.Condition((s, d, value) => value != null));

And my mapping call

var context = PatcherProfileContext.Create();

var originalEntity = new TestEntity
{
    Dictionary = new Dictionary<string, object> { { "key", "value" } }
};

var patchEntity = new TestEntity
{
    Dictionary = null
};

context.Mapper.Map(patchEntity, originalEntity);

originalEntity.Dictionary.ShouldHaveSingleItem();

But It winds up being empty.

Cyril Durand
  • 15,834
  • 5
  • 54
  • 62
  • Per the [automapper documentation](http://docs.automapper.org/en/stable/Lists-and-arrays.html#handling-null-collections), I do not think this is the expected behavior. Which version of Automapper are you using? –  Jan 10 '20 at 17:07
  • I am using Automapper 8.1.1 – ThreadSafe617 Jan 10 '20 at 18:27
  • It's my opinion that this is a bug in Automapper 8.1.1, but I am not positive. That version is only a few months old, and only one version has been released since. I seached Automapper's [issue tracker](https://github.com/AutoMapper/AutoMapper/issues?utf8=%E2%9C%93&q=is%3Aissue+AllowNullCollections+dictionary) but don't see anything like this reported. (I wouldn't report it as a bug until you have a second opinion here on SO.) –  Jan 10 '20 at 18:32
  • When mapping to an existing collection, the destination collection is cleared first. If this is not what you want, take a look at AutoMapper.Collection. – Lucian Bargaoanu Jan 10 '20 at 19:33

1 Answers1

0

I have realized, with help from Lucian, that the default behavior of mapping to an existing collection is to clear that collection out, regardless of if AllowNullCollections = true. I found an old stackoverflow post detailing that I should use precondition instead of regular condition in this case. I think this will work for me: Automapper does not map properly null List member, when the condition != null is specified