Non-nullable property must contain a non-null value warning on EF relationships

Viewed 997

C# compiler shows me Non-nullable property must contain a non-null value on:

  • EF relationships
  • DbSet

According to this documentation: Working with Nullable Reference Types I could get rid of this warning for DbSet using:

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

What is the best way to get rid of this warning for EF relationships as well for the following example below (without using #pragma warning disable CS8618) ?

public class Customer
{
    public Guid CustomerId { get; set; } = Guid.NewGuid();
    public string Username { get; set; }
    public virtual IEnumerable<Order> Orders { get; set; }

    public Customer(string username)
    {
        // still gets warning for `Orders`
        Username = username;
    }
}

And on the other side of relationship:

public class Order
{
    public Guid OrderId { get; set; } = Guid.NewGuid();
    public string Description { get; set; }
    public Guid CustomerId { get; set; }
    public virtual Job Job { get; set; }

    public Log(string description, Guid customerId)
    {
        // still gets warning for `Job`
        Description = description;
        CustomerId = customerId;
    }
}
1 Answers

Answering my own question I believe this is the most suitable way of removing warning in EF relationships:

public class Customer
{
    public Guid CustomerId { get; set; } = Guid.NewGuid();
    public string Username { get; set; }
    public virtual IEnumerable<Order> Orders { get; set; } = null!;

    public Customer(string username)
    {
        Username = username;
    }
}

And on the other side of relationship:

public class Order
{
    public Guid OrderId { get; set; } = Guid.NewGuid();
    public string Description { get; set; }
    public Guid CustomerId { get; set; }
    public virtual Job Job { get; set; } = null!;

    public Log(string description, Guid customerId)
    {
        Description = description;
        CustomerId = customerId;
    }
}

But if someone has a better idea please feel free to share it.

Related