我正在尝试创建一个代码优先的类,其中可能存在也可能不存在外键关系。我的类(class)是
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
最佳答案
答案是您也必须在导航属性上具有可选属性。所以在模型中我改为
[ForeignKey("InventoryID")]
public virtual Inventory? Inventory { get; set; }
问题已解决。
关于c# - 无法使用 efcore 创建可为空的外键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70530650/