实体框架核心级联删除错误
Posted
技术标签:
【中文标题】实体框架核心级联删除错误【英文标题】:Entity Framework Core Cascade Delete Error 【发布时间】:2020-02-10 15:50:22 【问题描述】:虽然在外键“FK_TeamMember_Teams_TeamId”上已设置为 on-delete:“ReferentialAction.Restrict”,但在尝试从 TeamMember 表中删除记录时会出现以下错误。你能帮我解决这个错误吗?
Microsoft.EntityFrameworkCore.DbUpdateException: An error occurred while updating the entries.
See the inner exception for details.
---> Microsoft.Data.SqlClient.SqlException (0x80131904): The DELETE statement conflicted with the
REFERENCE constraint "FK_TeamMember_Teams_TeamId". The conflict occurred in database "mot", table
"dbo.TeamMember", column 'TeamId'. The statement has been terminated.
以下是迁移代码块
migrationBuilder.CreateTable(
name: "TeamMember",
columns: table => new
Id = table.Column<Guid>(nullable: false),
MarketingOfficerId = table.Column<Guid>(nullable: false),
TeamId = table.Column<Guid>(nullable: true)
,
constraints: table =>
table.PrimaryKey("PK_TeamMember", x => x.Id);
table.ForeignKey(
name: "FK_TeamMember_Employees_MarketingOfficerId",
column: x => x.MarketingOfficerId,
principalTable: "Employees",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
table.ForeignKey(
name: "FK_TeamMember_Teams_TeamId",
column: x => x.TeamId,
principalTable: "Teams",
principalColumn: "Id",
onDelete: ReferentialAction.Restrict);
);
OnModelCreating 方法我也使用了以下方法。
modelBuilder.Entity<Team>()
.HasMany(i => i.TeamMembers)
.WithOne(i=>i.Team)
.OnDelete(DeleteBehavior.Restrict);
谢谢
【问题讨论】:
您使用的是哪个版本的 EF Core? 实体框架核心 v3.1.1 【参考方案1】:我认为这种行为是正确的,因为当主表删除一条记录时,它应该删除明细表中的相关记录。保留它没有意义。数据将是多余的。但是,如果我们想制作这样的场景,尽管我们在 migration.cs 中将 CascadeDelete 设置为 Restrict,但它不会按预期工作。以下文章将有助于理解这些行为。
https://docs.microsoft.com/en-us/ef/core/saving/cascade-delete
【讨论】:
以上是关于实体框架核心级联删除错误的主要内容,如果未能解决你的问题,请参考以下文章