首页 问答 C# 项目(csproj)启用 Nullable 设置竟然会影响到 EF Core 的映射
问题详情

昨天将一个 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)
   ...

回答

通过 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.

版权:言论仅代表个人观点,不代表官方立场。转载请注明出处:https://www.stntk.com/question/2523.html

发表评论
暂无评论

还没有评论呢,快来抢沙发~

点击联系客服

在线时间:8:00-16:00

客服QQ

70068002

客服电话

400-888-8888

客服邮箱

70068002@qq.com

扫描二维码

关注微信公众号

扫描二维码

手机访问本站