首页 新闻 会员 周边

C# 项目(csproj)启用 Nullable 设置竟然会影响到 EF Core 的映射

0
悬赏园豆:30 [已解决问题] 解决于 2026-02-24 13:19

昨天将一个 Domain Entities 所在的项目启用 Nullable 设置

<Project Sdk="Microsoft.NET.Sdk">
  <PropertyGroup>
    <Nullable>enable</Nullable>
  </PropertyGroup>
</Project>

没改任何代码,可以为空的实体属性没有加上 ?

运行时却出现下面的错误:

System.Data.SqlTypes.SqlNullValueException: Data is Null. This method or property cannot be called on Null values.
   at Microsoft.Data.SqlClient.SqlBuffer.ThrowIfNull()
   at Microsoft.Data.SqlClient.SqlBuffer.get_String()
   at Microsoft.Data.SqlClient.SqlDataReader.GetString(Int32 i)
   at lambda_method24(Closure, DbDataReader, Int32[])
   at Microsoft.EntityFrameworkCore.Query.Internal.BufferedDataReader.BufferedDataRecord.ReadObject(DbDataReader reader, Int32 ordinal, ReaderColumn column)
   ...
dudu的主页 dudu | 高人七级 | 园豆:23476
提问于:2026-02-22 10:23
< >
分享
最佳答案
0

通过 EF Core 的帮助文档 Working with Nullable Reference Types 知道了答案

Exercise caution when enabling nullable reference types on an existing project: reference type properties which were previously configured as optional will now be configured as required, unless they are explicitly annotated to be nullable. When managing a relational database schema, this may cause migrations to be generated which alter the database column's nullability.

dudu | 高人七级 |园豆:23476 | 2026-02-24 13:19
清除回答草稿
   您需要登录以后才能回答,未注册用户请先注册