【问题标题】:Unable to create nullable foreign key using efcore无法使用 efcore 创建可为空的外键
【发布时间】:2021-12-30 10:56:25
【问题描述】:

我正在尝试创建一个代码优先类,其中可能存在或不存在外键关系。我的课是

public class InventoryReturn
{
  [Key]
  [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
  [Required]
  public int InventoryReturnID { get; set; }

  [Required]
  public int ReturnType { get; set; }

  public int SerialNumber;

  public int? InventoryID { get; set; }

  [ForeignKey("InventoryID")]
  public virtual Inventory Inventory { get; set; }

}

这里我已将 InventoryID 指定为可选,但是当我尝试添加一行但未指定它时,出现错误

MySqlConnector.MySqlException (0x80084005): Cannot add or update a child row: a foreign key constraint fails

我尝试使用 dotnet ef 迁移脚本为此生成 mysql 迁移脚本,发现生成了以下脚本

CREATE TABLE `InventoryReturns` (
`InventoryReturnID` int NOT NULL AUTO_INCREMENT,
`ReturnType` int NOT NULL,
`InventoryID` int NOT NULL,
CONSTRAINT `PK_InventoryReturns` PRIMARY KEY (`InventoryReturnID`),
CONSTRAINT `FK_InventoryReturns_Inventories_InventoryID` FOREIGN KEY (`InventoryID`) REFERENCES `Inventories` (`InventoryID`) ON DELETE CASCADE
) CHARACTER SET=utf8mb4;

这里显示 InventoryID NOT NULL。

为什么会这样,我用的是Pomelo.EntityFrameworkCore.MySql

【问题讨论】:

  • 由于 EF 为 InventoryID 生成了一个 NOT NULL 列,您可能有一些映射代码可以根据需要对其进行配置。
  • @GertArnold 我正在使用自动映射器,但没有“必需”
  • Inventory 长什么样子? (班上)。我的意思是像OnModelCreating中的EF映射代码。

标签: c# entity-framework-core pomelo-entityframeworkcore-mysql


【解决方案1】:

你可能需要这个

modelBuilder
    .Entity<InventoryReturn>()
    .HasOptional<Inventory>(u => u.Inventory)
    .WithOptionalPrincipal();

source1 source2

【讨论】:

  • 它显示语法错误:“EntityTypeBuilder”不包含“HasOptional”的定义
  • 试试这个:.HasOne(u => u.Inventory)
【解决方案2】:

答案是你必须在导航属性上也有可选的。所以在模型中我改为

[ForeignKey("InventoryID")]
public virtual Inventory? Inventory { get; set; }

问题已解决。

【讨论】:

    猜你喜欢
    • 2022-01-08
    • 1970-01-01
    • 2010-11-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多