Non nullable property warning in DBcontext class for dbset property

2.3k Views Asked by At

I have my database context class as below

public class DataContext : DbContext
{
    public DataContext(DbContextOptions options) : base(options) 
    {
    }
    
    public DbSet<Customer> Customers;
    public DbSet<Order> Orders;
}

it warns saying

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

I have two options in hand to resolve but not sure which is good.

Option 1) make the property as nullable

public DbSet<Order>? Orders;

Option 2) set the property to empty set in constructor

public DataContext(DbContextOptions options) : base(options) 
    {
        this.Orders =  this.Set<Order>();
    }

Which one is the best option to resolve this warning and which also support test cases. ?

2

There are 2 best solutions below

1
PhonicUK On

Because a DbSet<T> is (for all practical purposes) guaranteed to be populated by EF once you create a context, you can set it to null! without changing the actual type:

    public DbSet<Customer> Customers {get;set;} = null!;
    public DbSet<Order> Orders {get;set;} = null!;

This will satisfy the non-nullable requirements without also upsetting EF.

null! is essentially a way of telling the compiler "I know you think this is going to be null, but I know better and know it won't be null by the time I need it - so don't warn me about it."

2
Stephan On

Starting with C#11 (.NET 7) one can 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<Customer> Customers {get;set;}
public required DbSet<Order> Orders {get;set;}

Edit: another option according to Microsoft is:

public DbSet<Customer> Customers => Set<Customer>();
public DbSet<Order> Orders => Set<Orders>()