首页 > 解决方案 > 自动映射器和空字典

问题描述

我正在使用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();

但它最终是空的。

标签: c#dictionaryautomapper

解决方案


我已经意识到,在 Lucian 的帮助下,映射到现有集合的默认行为是清除该集合,无论 AllowNullCollections = true 是否。我发现一个旧的 stackoverflow 帖子详细说明在这种情况下我应该使用前置条件而不是常规条件。我认为这对我有用:Automapper 没有正确映射空列表成员,当条件 != null 被指定时


推荐阅读