c# - EF Core 3.0 可为空的导航属性

标签 c# .net-core entity-framework-core c#-8.0 entity-framework-core-3.0

因此 EF Core 预览版 7 发布了,我决定将它与 C# 8 预览版和 .NET Core 3.0 预览版 7 一起使用。假设我有一个表示多对多关系的类:

public class A 
{
    public int Id { get; set; }
    public ICollection<Relation> Relations { get; set; }
}

public class B
{
    public int Id { get; set; }
    public ICollection<Relation> Relations { get; set; }
}

public class Relation
{
    public A A { get; set; }
    public B B { get; set; }

    public int AId { get; set; }
    public int BId { get; set; }
}

我将它们映射为:

modelBuilder.Entity<A>(entity => entity.HasKey(e => e.Id));

modelBuilder.Entity<B>(entity => entity.HasKey(e => e.Id));

modelBuilder.Entity<Relation>(entity =>
{
    entity.HasKey(e => new { e.AId, e.BId });

    entity.HasOne(e => e.A).WithMany(a => a.Relations).HasForeignKey(e => e.AId);

    entity.HasOne(e => e.B).WithMany(b => b.Relations).HasForeignKey(e => e.BId);
});

现在,由于我可能不想包含一个或两个关系类,AB 可以为空。因此,它们应该可以为空。

var relation = Set<Relations>().Include(r => r.A).First(); // relation.A is not null, but relation.B is null.

所以我将类重写为:

public class Relation
{
    public A? A { get; set; }
    public B? B { get; set; }
}

但是现在模型构建不起作用,因为这些行:

entity.HasOne(e => e.A).WithMany(a => a.Relations).HasForeignKey(e => e.AId);

entity.HasOne(e => e.B).WithMany(b => b.Relations).HasForeignKey(e => e.BId);

raise CS8602 - 在 a.Relationsb.Relations 访问上取消引用可能为空的引用,我将其设置为处理作为解决方案范围内的错误,因为这似乎是一件理智的事情。

请注意,从另一侧构建模型,因此在 AB 上配置 HasMany,将引发 CS8603 - 可能为 null引用返回

我能够通过 #pragma warning disable CS8602 悄悄解决这个问题,但这显然是一种解决方法。在我看来,它像是 EF Core 中的一种味道,这种用法是正确的,并且不会引发任何 null 问题。但是,我无法在 EF Core 的 github 上找到此类问题。

所以问题是,在当前的 EF Core 3.0.0 Preview 7 中,有没有一种方法可以在不对模型构建发出警告的情况下拥有可为空的导航属性?如果不是,这确实是一个问题,它是否已知并且我在 EF Core 的 github 上错过了它,或者我应该在那里提出它?

最佳答案

正如下面链接中提到的,您可以使用 null-forgiving 运算符 (!) https://learn.microsoft.com/en-us/ef/core/miscellaneous/nullable-reference-types

所以你的代码必须是:

entity.HasOne(e => e.A!).WithMany(a => a.Relations).HasForeignKey(e => e.AId);

entity.HasOne(e => e.B!).WithMany(b => b.Relations).HasForeignKey(e => e.BId);

关于c# - EF Core 3.0 可为空的导航属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57251062/

相关文章:

c# - 使用 IObserver/IObservable 实现观察者和主题

c# - 在 C# 中组合两个 lambda 表达式

c# - 如何将 ASP.NET Core Identity 用户作为 EF 迁移的一部分

c# - 获取 - System.InvalidOperationException - 客户端投影包含对常量表达式的引用

c# - 表达式中未定义的函数 'Replace' ,是否替换?

c# - 如何使用 txt 文件作为命令行参数?

c# - 我可以在 .NET Standard 类库中使用动态吗?

c# - 重定向到页面 OnActionExecuting 方法 ASP.NET Core 5 MVC

c# - Asp.Net Core 3.1 Appsettings 不尊重 JsonConverter

c# - 如何在 xUnit 测试项目中正确设置 DbContext?