自动映射器和空字典

时间:2020-01-10 16:19:48

标签: c# dictionary automapper

我正在使用 Automapper 将对象修补到其自身上。

在执行映射时,我想忽略源对象中的null值。这适用于使用AllowNullCollections = true;的集合。当我有一个包含带有一些元素的字典的目标对象,并且尝试映射包含一个空字典的源对象时,我希望该空字典被忽略,因为我忽略了空集合。

但是在我的目标对象上,字典空了。 这是字典的预期行为吗?

这是我的个人资料

AllowNullCollections = true;

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

我的地图通话

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();

但是最终它是空的。

1 个答案:

答案 0 :(得分:0)

我已经意识到,在Lucian的帮助下,映射到现有集合的默认行为是清除该集合,而不管AllowNullCollections = true。我发现了一个旧的stackoverflow帖子,其中详细说明了在这种情况下我应该使用前置条件而不是常规条件。我认为这对我有用:Automapper does not map properly null List member, when the condition != null is specified