繁体   English   中英

实体框架核心级联删除错误

[英]Entity Framework Core Cascade Delete Error

尽管已将其设置为 on-delete: "ReferentialAction.Restrict" 外键 "FK_TeamMember_Teams_TeamId",但在尝试从 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);


谢谢你

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM