Entity Framework核心级联删除错误

Entity Framework Core Cascade Delete Error

虽然它已设置为 on-delete: "ReferentialAction.Restrict" 在外键 "FK_TeamMember_Teams_TeamId" 上,但在尝试从 TeamMember table 中删除记录时会出现以下错误。你能帮我解决这个错误吗?

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);


谢谢

我认为这种行为是正确的,因为当主 table 删除一条记录时,它应该删除详细信息 table 中的相关记录。保留它没有意义。数据将是冗余的。但是,如果我们想要实现这样的场景,尽管我们在 migration.cs 内将 CascadeDelete 设置为 Restrict,但它不会按预期工作。以下文章将有助于理解这些行为。

https://docs.microsoft.com/en-us/ef/core/saving/cascade-delete