c# - 自动映射器和空字典
问题描述
我正在使用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 没有正确映射空列表成员,当条件 != null 被指定时
推荐阅读
- javascript - 如何使用 axios 将图像作为应用程序/json 数据发布到 REST 端点?
- python - 如何删除一个带有两个特定初始单词的句子
- c++ - 重置 std::shared_ptr 是否会导致重置其删除器?
- postgresql - 架构 pgagent 的权限被拒绝
- python - python - 如何将字典的值与函数一起添加
- reactjs - reactjs iterate over a array in functional component
- javascript - 在文件夹中的html中显示多个图像
- php - PHP paypal 商务平台(api v2)合作伙伴没有得到报酬?
- kubernetes - Kubespray Kubernetes 安装失败 - dockerd[8296]:无法使用文件 /etc/docker/daemon.json 配置 Docker 守护进程
- python-3.x - 无法通过 API Gateway 将对象解析为事件以获取 Lambda 的响应?