尽管已将其设置为on-delete:外键“ FK_TeamMember_Teams_TeamId”上的“ 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);
谢谢
答案 0 :(得分:0)
我认为这种行为是正确的,因为当主表删除记录时,它应该删除明细表中的相关记录。保留它毫无意义。数据将是冗余的。但是,如果我们要制作这样的场景,尽管我们在migration.cs中将CascadeDelete设置为Restrict,但它不会按预期工作。下面的文章将有助于理解其行为。
https://docs.microsoft.com/en-us/ef/core/saving/cascade-delete