【问题标题】:.Net Core Fluent API with Nullable references types具有 Nullable 引用类型的 .Net Core Fluent API
【发布时间】:2020-06-09 14:51:21
【问题描述】:

我似乎无法解决以下问题,也找不到任何在线帮助。我是 .Net Core 的新手,对使用可为空的引用类型也很陌生,不知何故我无法让它们与 EF Core 一起工作。我有一个包含一对多关系的数据表,其中外键可以为空(即关系中可能没有项目 - 在本例中,并非所有资产都有 AssetTypes)。曾经工作的 fluent API 是

modelBuilder.Entity<Asset>(entity =>
{
    entity.HasOne(d => d.AssetType)
          .WithMany(p => p.Assets)
          .HasForeignKey(d => d.AssetTypeId)
          .HasConstraintName("FK_Assets_AssetTypes");}

问题出在AssetType?可以为空我现在得到一个

'p' 在这里可能为空...关于 p.Assets 的警告

除了压制消息并希望它有效之外,似乎无法找到解决方法,尽管其他多对多关系不需要并且需要手动处理,但似乎是这样。除非我做错了,否则 EFCore 在多对多上似乎非常原始。

我尝试从 AssetType 实体开始反转关系,但我得到了类似的结果。

我也试过

.WithMany() 

但这会删除现有的导航属性,因此它不起作用。

任何帮助将不胜感激,因为我显然遗漏了一些东西。

【问题讨论】:

    标签: ef-fluent-api nullable-reference-types


    【解决方案1】:

    我刚刚在配置映射表达式时遇到了类似的情况。最后,我决定让警告静音,因为所写的表达式永远不会执行。它仅由 EF 解析以执行其内部魔术。你的情况是这样的(无需处理#pragma warning disable

    modelBuilder.Entity<Asset>(entity =>
    {
        entity.HasOne(d => d.AssetType)
              .WithMany(p => p.Assets!)
                                  // ^ this '!' tells to compiler to stop bothering you about this
                                  // null dereference because you are sure the code is right
              .HasForeignKey(d => d.AssetTypeId)
              .HasConstraintName("FK_Assets_AssetTypes");
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-02-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-01-24
      • 1970-01-01
      相关资源
      最近更新 更多