ASP.NET Core 2.1升级到3.1后调用接口抛出SqlNullValueException异常
异常原因
从你提供的堆栈信息可以明确,异常并不是前端传值绑定导致,而是EF Core查询数据库时的可空性校验不通过:
查询返回的结果集中存在字符串类型的NULL值,但你映射结果的实体类中对应属性是不可为空的string类型,.NET Core 3.x 版本开始默认启用严格的可空引用类型校验,EF Core 3.x 也同步升级了校验逻辑,遇到空值会直接抛出异常,而不是像2.x版本一样静默赋值为默认值。
解决步骤
1. 修复实体类可空性定义
- 检查
MantenimientoLogsRepository.GetIdRegistro()方法中查询用到的实体类,所有对应数据库允许为NULL的字符串字段,将属性类型从string修改为string?(可空引用类型) - 如果你不需要启用可空引用类型校验,可以在实体类所在项目的
.csproj文件中移除<Nullable>enable</Nullable>配置,或者给允许为空的属性添加[AllowNull]特性
2. 清理脏数据或调整查询逻辑
- 如果你确定该字段业务上不允许为NULL,直接清理数据库中该字段的NULL值,统一更新为合理的默认值(如空字符串)
- 也可以在查询时增加空值处理逻辑,示例如下:
var queryResult = dbContext.YourTable .Select(x => new YourEntity { TargetField = x.TargetField ?? string.Empty, // 其他字段赋值 }) .ToList();
3. 修复Startup配置冲突
你当前的配置同时注册了AddMvc()和AddControllers(),还混用了两套JSON序列化规则,这是你修改配置后出现其他错误的核心原因,ASP.NET Core 3.1 中只需要保留AddControllers()即可,修改后的ConfigureServices代码如下:
public void ConfigureServices(IServiceCollection services) { // 删除原来的AddMvc及相关System.Text.Json配置 services.AddControllers(options => { options.EnableEndpointRouting = true; options.SuppressImplicitRequiredAttributeForNonNullableReferenceTypes = true; options.AllowEmptyInputInBodyModelBinding = true; }) .AddNewtonsoftJson(options => { options.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore; options.SerializerSettings.NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore; options.SerializerSettings.ContractResolver = new Newtonsoft.Json.Serialization.DefaultContractResolver(); options.SerializerSettings.DateFormatString = "dd-MM-yyyy"; }); // 保留原有DbContext配置 services.AddDbContextPool<PegasusDbContext>(options => options.UseSqlServer(Configuration.GetConnectionString("PegasusDb"))); services.AddDbContextPool<ServicesDbContext>(options => options.UseSqlServer(Configuration.GetConnectionString("ServicesDb"), sqlServerOptions => sqlServerOptions.CommandTimeout(180))); }
内容的提问来源于stack exchange,提问作者Dani
相关产品推荐
相关产品推荐

