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. ?
Because a
DbSet<T>is (for all practical purposes) guaranteed to be populated by EF once you create a context, you can set it tonull!without changing the actual type: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."