【问题标题】:How can I resolve .NET Core with EF Core required field error?如何解决 .NET Core 与 EF Core 必填字段错误?
【发布时间】:2022-08-03 09:16:33
【问题描述】:

我有一个 .NET Core (6.0.1) API,它是使用带有 EF Core (6.0.1) 的 DB first 方法构建的。每当我尝试发布到特定实体时,我都会收到实体中导航属性之一的“必填字段”错误。我还有其他几个以类似方式构建的实体,它们似乎工作正常,但这一个给我带来了问题,我无法弄清楚。有任何想法吗?

来自 DBContext:

    modelBuilder.Entity<InsuranceCompanyStatus>(entity =>
        {
            entity.HasKey(e => e.InsCoStatusId);

            entity.ToTable(\"InsuranceCompanyStatus\");

            entity.Property(e => e.InsCoStatusId).HasColumnName(\"InsCoStatusID\");

            entity.Property(e => e.InsuranceCompanyId).HasColumnName(\"InsuranceCompanyID\");

            entity.Property(e => e.State)
                .HasMaxLength(2)
                .IsUnicode(false)
                .IsFixedLength();

            entity.HasOne(d => d.InsuranceCompany)
                .WithMany(p => p.InsuranceCompanyStatuses)
                .HasForeignKey(d => d.InsuranceCompanyId)
                .HasConstraintName(\"FK_InsuranceCompanyStatus_InsuranceCompanies\");
        });

脚手架型号:

    public partial class InsuranceCompanyStatus
    {
      public int InsCoStatusId { get; set; }
      public Guid InsuranceCompanyId { get; set; }
      public string State { get; set; } = null!;
      public bool Admitted { get; set; }
      public bool? Approved { get; set; }

      public virtual InsuranceCompany InsuranceCompany { get; set; } = null!;
    }

来自尝试的 POST 正文的 JSON:

    {
     \"insuranceCompanyId\": \"caa3e956-a3be-4670-83e3-53a6ec47731e\",
     \"state\": \"AL\",
     \"admitted\": true,
     \"approved\": true
    }

错误响应状态为 400:

    {
     \"type\": \"https://tools.ietf.org/html/rfc7231#section-6.5.1\",
     \"title\": \"One or more validation errors occurred.\",
     \"status\": 400,
     \"traceId\": \"00-cf1de6fe8e4fb67a04ff7d4c8b6a1c68-f426059123424d72-00\",
     \"errors\": {
        \"InsuranceCompany\": [
        \"The InsuranceCompany field is required.\"
     ]
    }
    }
  • 很高兴看到类和映射以及发布的内容,但问题中绝不应该缺少引发异常的实际运行代码。

标签: c# .net-core entity-framework-core


【解决方案1】:

您必须将 InsuranceCompanyId 设为可为空

public partial class InsuranceCompanyStatus
{
    public int InsCoStatusId { get; set; }
    
    ....
    public Guid? InsuranceCompanyId { get; set; }
    
    public virtual InsuranceCompany InsuranceCompany { get; set; }  // = null!; you don't need it , it is null by default
}

它通常可以工作,但如果仍然无法正常工作,您可以在 fluent appi 中显式添加它

 modelBuilder.Entity<InsuranceCompanyStatus>(entity =>
 {
   .....  
   entity.Property(e => e.InsuranceCompanyId).IsOptional(); 

【讨论】:

    【解决方案2】:

    我有这样的场景:

    • 我的表中有一个 NOT NULL 外键;
    • C# 8.0 引入了nullable reference types - 是的,声明其数据类型的变量的类型指定是可以为空的引用(我认为这是含蓄的,但here 对他们的案子有一些澄清);
    • EF 6 started using it

    当我尝试插入新记录时,我在 FK 导航属性上收到“必填字段”错误。如果我将 FK 更改为数据库中的可空列并重新构建代码,一切正常。

    related EFCore Github project issue 中有一些基本原理和“设计决定”,但我无法消化它,所以我选择了简单的方法。

    这是原始 EF 生成的代码:

    namespace DAback.Models
    {
        public partial class Patient
        {
            // ...
            public int CurrentQueue { get; set; }  // FK to Queue table
    
            public virtual Queue CurrentQueueNavigation { get; set; } = null!;
        }
    

    生成“字段是必需的”错误是因为提供给插入方法的对象在当前队列导航财产(虽然当前队列被填充)。

    我在这里尝试了关于将 get/set 属性声明为可为空,以及在上下文初始化期间将脚手架属性设置为不需要的建议(OnModelCreating) 但没有。所以我将导航属性类型声明为可以为空的引用类型并且一切正常:

    namespace DAback.Models
    {
        public partial class Patient
        {
            // ...
            public int CurrentQueue { get; set; }  // FK to Queue table
    
            // Using "Queue?" instead of "Queue" so EF now knows this
            // object doesn't need to be present on deserialization
            // i.e., it can be null
            public virtual Queue? CurrentQueueNavigation { get; set; } = null!;
        }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-01-02
      • 2018-01-15
      • 2018-03-07
      • 2018-12-25
      • 2017-03-28
      相关资源
      最近更新 更多