Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Non-nullable warning with EF core DbSet

If I have a DbContext as follows (which is a standard db context):

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; }
}

I have nullable reference types turned on.

I get a warning on the constructor:

Non-nullable property 'Audit' must contain a non-null value when exiting constructor. Consider declaring the property as nullable.

How can I get make this warning go away (and keep the interface)?

like image 847
Sun Avatar asked Mar 07 '26 10:03

Sun


2 Answers

I've just fixed it like this. Need to make the property read only.

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

public interface IAudit
{
    DbSet<Audit> Audit { get; }
}
like image 179
Sun Avatar answered Mar 09 '26 00:03

Sun


For completeness, starting with C#11 (.NET 7) one can also use the required modifier to mark that a property needs to be set by an object initializer. Since we don't manually instance the DbContext, we can therefore use it in this case:

public required DbSet<Audit> Audit { get; set; }
like image 24
Stephan Avatar answered Mar 08 '26 23:03

Stephan