Search code examples
entity-framework-coreforeign-keysblazorcode-first

Remap foreign key constraint after table rename with EF Core code first migration


I have to rename a table A that is targetted by a foreign key constraint of another table C. I then have to add a new table B and remap the old foreign key constraint link "A <-> B" to C, so that now B and C are linked.

How can I do that with Blazor, EF core code first? It would be ok the remove the foreign key constraint "A <-> C" and create a new "B <-> C" one. I just don't know how to write that down as C# migration code.

Background: The automatically created migration didn't work due to exactly that foreign key restriction. Instead of simply renaming everything, code for dropping the table and recreating it was created, causing a foreign key constraint error during execution of the migration. So I rewrote it to simply rename the table and create the new one, but that remapped the foreign key to the renamed table, which is not what is needed.


Solution

  • I found the answer myself: I can use migrationBuider.DropForeignKey() and migrationBuilder.AddForeignKey().