After upgrading from EF Core 8 to EF Core 9, we encountered a regression where using migrationBuilder.DropTable followed by recreating the same table in a single migration causes issues. The issue seems to be resolved when switching to a raw SQL command (migrationBuilder.Sql("DROP TABLE ...");) to drop the table instead of using migrationBuilder.DropTable.
protected override void Up(MigrationBuilder migrationBuilder)
{
// Assuming table Employees was previously created...
// DropTable: causes the migration to fail
migrationBuilder.DropTable(
name: "Employees");
// Uncomment this (and comment out DropTable) to run the migration successfully
//migrationBuilder.Sql("""
// Drop Table Employees;
// """);
// Recreate table
migrationBuilder.CreateTable(
name: "Employees",
columns: table => new
{
EmployeeId = table.Column<int>(type: "int", nullable: false)
.Annotation("SqlServer:Identity", "1, 1"),
Name = table.Column<string>(type: "nvarchar(max)", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_Employees", x => x.EmployeeId);
});
}
Exception & stack tack traces
System.Collections.Generic.KeyNotFoundException: 'The given key '(Employees, )' was not present in the dictionary.'
EF Core version: 9.0.0
Database provider: Microsoft SQL Server (LocalDB)
Target framework: .NET 9.0
Operating system: Windows 11
IDE: Visual Studio 2022 17.12.0
Problem
After upgrading from EF Core 8 to EF Core 9, we encountered a regression where using
migrationBuilder.DropTable
followed by recreating the same table in a single migration causes issues. The issue seems to be resolved when switching to a raw SQL command (migrationBuilder.Sql("DROP TABLE ...");
) to drop the table instead of usingmigrationBuilder.DropTable
.Exception & stack tack traces
Versions
EF Core version: 9.0.0 Database provider: Microsoft SQL Server (LocalDB) Target framework: .NET 9.0 Operating system: Windows 11 IDE: Visual Studio 2022 17.12.0