C#编译器在上显示Non-nullable property must contain a non-null value
- EF
relationships
DbSet
根据本文档:使用可为null的引用类型,我可以使用消除DbSet
的此警告
public class DataContext : DbContext
{
public DataContext(DbContextOptions options) : base(options) {}
public DbSet<Customer> Customers => Set<Customer>();
public DbSet<Order> Orders => Set<Order>();
}
对于EFrelationships
以及下面的示例(不使用#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;
}
}
回答我自己的问题时,我认为这是删除EFrelationships
:中警告的最合适方法
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;
}
}
但如果有人有更好的想法,请随时分享。