处理 Net 6 中的可空实体和实体框架实体

Mig*_*ura 8 c# entity-framework-core .net-core .net-6.0

使用 Net 6 和实体框架我有以下实体:

public class Address {

  public Int32 Id { get; set; }
  public String CountryCode { get; set; }  
  public String Locality { get; set; }
  public Point Location { get; set; }

  public virtual Country Country { get; set; }
  public virtual ICollection<User> Users { get; set; } = new List<User>();  

}
Run Code Online (Sandbox Code Playgroud)

在项目定义中<Nullable>enable</Nullable>,我收到警告:

Non-nullable property '...' must contain a non-null value when exiting constructor. Consider declaring the property as nullable. 
Run Code Online (Sandbox Code Playgroud)

在地址属性中:

CountryCode, Locality, Location and Country.
Run Code Online (Sandbox Code Playgroud)

我看到有几个选项可以解决这个问题:

public String? CountryCode { get; set; } 

public String CountryCode { get; set; } = null!; 
Run Code Online (Sandbox Code Playgroud)

我还可以添加构造函数,但并非所有属性(例如导航属性)都可以在构造函数中。

解决这个问题的方法是什么?

Luk*_* Vo 15

从 .NET 7 开始,您可以使用必需属性来代替:

public required Product Product { get; set; } // Add required keyword
Run Code Online (Sandbox Code Playgroud)

之前的回答

就我个人而言,我只是将这一行放在所有模型文件(POCO/JSON 模型、DbContext 等)的顶部:

#pragma warning disable CS8618 // Non-nullable field must contain a non-null value when exiting constructor. Consider declaring as nullable.
Run Code Online (Sandbox Code Playgroud)

只需将该行放在文件顶部即可,不需要restore

还有另一个“官方”解决方案,但它很糟糕:

public Product Product { get; set; } = null!;
Run Code Online (Sandbox Code Playgroud)

无论如何,该文档确实将我的解决方案列出为有效,但您不需要为每个属性重复它。

关于如何使用 VS 创建该行的提示:

在此输入图像描述

你会得到这样的东西:

#pragma warning disable CS8618 // Non-nullable field must contain a non-null value when exiting constructor. Consider declaring as nullable.
    public TestContext(DbContextOptions options) : base(options)
#pragma warning restore CS8618 // Non-nullable field must contain a non-null value when exiting constructor. Consider declaring as nullable.
Run Code Online (Sandbox Code Playgroud)

删除最后一行并将第一行剪切到文件顶部。


dot*_*tep 7

几天前我遇到了同样的事情,实际上 .net 5 中也存在可空引用类型,但我们必须手动将其添加到 .csproj 中,而在 .net 6 中它默认存在。

我采取了以下方法。

如果我知道我的属性不可为空,并且当迁移生成时它应该具有可为空的 false,那么我会这样写。

public string CountryCode { get; set;} = null!; // This indicate that this property will have value eventually. so no warning generate during compilation.
Run Code Online (Sandbox Code Playgroud)

当我知道属性可以包含 null 并且在数据库或迁移中也可以为 nullable = true 时

public string? CountryCode {get;set;}
Run Code Online (Sandbox Code Playgroud)