c# - 从集合中删除空值
问题描述
我们通常有这样的用例,即我们有一个在 ( new SomeType[]{null}
) 中包含一个空元素的集合。现在我们有一个扩展方法可以删除这些空元素,但显然我们必须为我们想要映射的每个集合配置它。
是否有一些通用的方法来告诉 automapper 从集合中删除空值,无论是全局还是每个配置文件?
解决方案
AotoMapper 提供条件映射
举个例子,
CreateMap<MyClassDTO, MyClass>()
.ForAllMembers(opts => opts.Condition((src, dest, srcMember) => srcMember != null));
在全局级别开启(未测试)
Mapper.Initialize(cfg =>
{
cfg.ForAllMaps((typeMap, map) =>
map.ForAllMembers(opts => opts.Condition((src, dest, srcMember) => srcMember != null));
}
推荐阅读
- mongodb - 如何在 mongodb atlas 中创建插入触发器?
- python - 如何通过 Spotipy 获取所有项目,包括下一页
- apache-flink - 由简单事件生成的复杂事件的建模时间
- php - Laravel 6 - Auth::guard('user')->user 返回 null
- ruby-on-rails - 如何强制 ActiveStorage::Attached#attach 同步运行——禁用异步行为
- flutter - Scrolling resets widgets flutter
- django - 如何在 Django 模板中使用换行符
- python - 如何为每日数据大小变化创建动态 INT 变量
- firebase - 是否有必要为 Firebase 身份验证清理数据?
- c# - Asp.net 控件在后面的代码中不可访问。出现错误'名称'txtUserEmail'在当前上下文中不存在'