Data is Null. This method or property cannot be called on Null values

如果数据库的记录 如果字段 LastName是Null的时候 并且 我们的Model这边没有定义成 string?
我们刚好查询到这条记录这个时候就会报出 Data is Null. This method or property cannot be called on Null values

    public class Customer
    {
        [Key]
        public int Id { get; set; }

        public string? FirstName { get; set; }

        public string LastName { get; set; }
    }

主要原因是可为空引用类型 https://learn.microsoft.com/zh-cn/dotnet/csharp/nullable-references

项目默认情况下是会报 下面的错。 CS8618 - Non-nullable variable must contain a non-null value when exiting constructor. Consider declaring it as nullable.

取消 可为空引用类型

如果不想启用这个功能。如果需要如下设置 或者直接去改项目文件。 右键点击 项目 -> Properties. Under the section Build -> General, set Nullable to Disable.

项目文件里面的 Nullable 就会被成 disable 这样我们就不需要 把 string 变成 string?

<Project Sdk="Microsoft.NET.Sdk">

 <PropertyGroup>
   <OutputType>Exe</OutputType>
   <TargetFramework>net6.0</TargetFramework>
   <ImplicitUsings>enable</ImplicitUsings>
   <Nullable>disable</Nullable>
 </PropertyGroup>
最近更新的
...