Entity Framework Core Cascade Delete Error

1

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. 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.

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


Thank You

asp.net
entity-framework
entity-framework-core
asp.net-core-webapi
webapi
asked on Stack Overflow Feb 10, 2020 by Pubudu

1 Answer

0

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. The following article will help with understanding the behaviours.

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

answered on Stack Overflow Feb 13, 2020 by Pubudu

User contributions licensed under CC BY-SA 3.0