EF core DbSet 的不可空警告

Sun*_*Sun 10 c# entity-framework-core c#-8.0 nullable-reference-types

如果我有一个 DbContext 如下(这是一个标准的数据库上下文):

public class MyContext : DbContext, IAudit
{
    public MyContext(DbContextOptions options) : base(options) { }
    
    public DbSet<Audit> Audit { get; set; }
}

public interface IAudit
{
    DbSet<Audit> Audit { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

我打开了可为空引用类型。

我收到关于构造函数的警告:

退出构造函数时,不可为空的属性“Audit”必须包含非空值。考虑将该属性声明为可为空。

我怎样才能让这个警告消失(并保留界面)?

Sun*_*Sun 13

我刚刚像这样修复了它。需要将属性设置为只读。

public class MyContext : DbContext, IAudit
{
    public MyContext(DbContextOptions options) : base(options) { }
    
    public DbSet<Audit> Audit => Set<Audit>()
}

public interface IAudit
{
    DbSet<Audit> Audit { get; }
}
Run Code Online (Sandbox Code Playgroud)

  • 为我指明了正确的方向。看到你的帖子后找到了这些官方文档。谢谢。https://learn.microsoft.com/en-us/ef/core/miscellaneous/nullable-reference-types (4认同)

Ste*_*han 7

为了完整起见,从 C#11 (.NET 7) 开始,还可以使用修饰符required来标记属性需要由对象初始值设定项设置。由于我们不手动实例化 DbContext,因此我们可以在这种情况下使用它:

public required DbSet<Audit> Audit { get; set; }
Run Code Online (Sandbox Code Playgroud)