You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

.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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.19 04:32:07