.NET Core 6全局配置MongoDB IgnoreNullValues示例(Program.cs)
.NET Core 6 Program.cs 全局配置 MongoDB 忽略空值示例
原 .NET Core 3.1 Startup.cs 配置代码
ConventionPack ignoreIfNullConvention = new ConventionPack(); ignoreIfNullConvention.Add(new IgnoreIfNullConvention(true)); ConventionRegistry.Register("ignoreIfNull", ignoreIfNullConvention, t => true);
.NET Core 6 Program.cs 实现方式
在 .NET 6 的顶级语句模式下,直接在 Program.cs 中完成全局约定注册即可,适配新的项目结构:
// 引入必要命名空间 using MongoDB.Bson.Serialization.Conventions; var builder = WebApplication.CreateBuilder(args); // 注册全局忽略空值约定 var ignoreIfNullConvention = new ConventionPack(); ignoreIfNullConvention.Add(new IgnoreIfNullConvention(true)); ConventionRegistry.Register("IgnoreNullValues", ignoreIfNullConvention, t => true); // 后续服务注册、应用构建逻辑 var app = builder.Build(); // ... 其他中间件配置代码 app.Run();
关键说明
- 代码逻辑和原 .NET Core 3.1 版本完全一致,仅适配了 .NET 6 的顶级语句结构
IgnoreIfNullConvention(true)表示插入或更新数据时,忽略所有值为null的字段- 约定注册必须在注册 MongoDB 上下文或客户端实例之前执行,确保全局生效
内容的提问来源于stack exchange,提问作者jstolz
相关产品推荐
相关产品推荐

