不可为空 属性 必须包含关于 EF 关系的非空值警告

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

C# 编译器显示 Non-nullable property must contain a non-null value 在:

根据此文档:Working with Nullable Reference Types 我可以使用以下方法消除 DbSet 的警告:

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

为 EF relationships 以及下面的示例 (不使用 #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;
    }
}

而在关系的另一边:

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

回答我自己的问题我认为这是在 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;
    }
}

而关系的另一边:

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

但如果有人有更好的想法,请随时分享。