【发布时间】: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