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)?
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; }
}
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; }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With