不能将值 NULL 插入列 'Address',表 'dbo.xxx';列不允许有 Null 值。INSERT 失败。检查数据库和迁移文件时发现Address这个字段被意外设置成nullable: false,而其它的字段却正常,按理来说对于string类型的属性,EFCore在codefirst模式下应该映射为可空类型。代码也确认了实体中不包含[Required]注释,在任何地方也没有出现.IsRequired()的调用。
<Nullable>enable</Nullable>
换而言之,启用了该功能后,把原本《引用类型可为空》的这个传统约定,更改称为了《引用类型是否可为空,是通过?语法来表明的》,实体中string类型的属性在C#中作为引用类型,自然而然地受到了这个影响。
果然,在删除了这个功能后,string?的语法将不起作用public class CustomerWithoutNullableReferenceTypes { public int Id { get; set; } // 堆代码 duidaima.com [Required] // Data annotations needed to configure as required public string FirstName { get; set; } [Required] public string LastName { get; set; } // Data annotations needed to configure as required public string MiddleName { get; set; } // Optional by convention }有NRT
public class Customer { public int Id { get; set; } public string FirstName { get; set; } // Required by convention public string LastName { get; set; } // Required by convention public string? MiddleName { get; set; } // Optional by convention // Note the following use of constructor binding, which avoids compiled warnings // for uninitialized non-nullable properties. public Customer(string firstName, string lastName, string? middleName = null) { FirstName = firstName; LastName = lastName; MiddleName = middleName; } }这两种模型的数据库映射是等价的。之后应留意项目的"NRT"功能是否开启,在解决方案.csproj文件中用如下方式关闭
<Nullable>disable</Nullable>留意实体类中是否有代码段被标识"NRT"功能开启
#nullable disable #nullable enable从 .NET 6 开始,默认情况下会为新项目启用这些功能。原始项目是.NET 5.0升级而来的,所以项目文件中并不会包含Nullable相关的配置。为了一行bug,好值得的一个下午呢!