【问题标题】:Non-nullable property must contain a non-null value warning on EF relationships不可为空的属性必须包含关于 EF 关系的非空值警告
【发布时间】:2022-01-07 02:26:11
【问题描述】:

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

  • EFrelationships
  • DbSet

根据本文档: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;
    }
}

【问题讨论】:

  • 你真的使用可为空的引用类型吗?

标签: c# entity-framework


【解决方案1】:

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

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

【讨论】:

  • 是的,我认为最好的方法是要么初始化它们,要么改变你的数据模型,但这样你就不能再使用可空类型了
猜你喜欢
  • 1970-01-01
  • 2021-08-02
  • 1970-01-01
  • 2017-01-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-07-21
相关资源
最近更新 更多