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