简体   繁体   English

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

[英]Entity Framework Core Cascade Delete Error

Though it has been set to on-delete: "ReferentialAction.Restrict" on foreign key "FK_TeamMember_Teams_TeamId", it gives the following error when trying to delete a record from TeamMember table.尽管已将其设置为 on-delete: "ReferentialAction.Restrict" 外键 "FK_TeamMember_Teams_TeamId",但在尝试从 TeamMember 表中删除记录时会出现以下错误。 Can you please help me with how I should get rid of this error?你能帮我解决这个错误吗?

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.    


Following is the migration code block以下是迁移代码块

  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 method I have used the following as well. OnModelCreating 方法我也使用了以下方法。

modelBuilder.Entity<Team>()
       .HasMany(i => i.TeamMembers)
       .WithOne(i=>i.Team)
       .OnDelete(DeleteBehavior.Restrict);


Thank You谢谢你

I think the behavior is correct since when the master table deletes a record it should delete its related records in the detail table.我认为这种行为是正确的,因为当主表删除一条记录时,它应该删除详细表中的相关记录。 No point in keeping it.保留它没有意义。 Data will be redundant.数据将是冗余的。 But in case if we want to make such a scenario, though we set CascadeDelete to Restrict within the migration.cs it will not work as expected.但是,如果我们想制作这样的场景,尽管我们在 migration.cs 中将 CascadeDelete 设置为 Restrict ,但它不会按预期工作。 The following article will help with understanding the behaviours.以下文章将有助于理解这些行为。

https://docs.microsoft.com/en-us/ef/core/saving/cascade-delete 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