Entity Framework Migrations renaming tables and columns
Nevermind. I was making this way more complicated than it really needed to be.
This was all that I needed. The rename methods just generate a call to the sp_rename system stored procedure and I guess that took care of everything, including the foreign keys with the new column name.
public override void Up(){ RenameTable("ReportSections", "ReportPages"); RenameTable("ReportSectionGroups", "ReportSections"); RenameColumn("ReportPages", "Group_Id", "Section_Id");}public override void Down(){ RenameColumn("ReportPages", "Section_Id", "Group_Id"); RenameTable("ReportSections", "ReportSectionGroups"); RenameTable("ReportPages", "ReportSections");}
If you don't like writing/changing the required code in the Migration class manually, you can follow a two-step approach which automatically make the RenameColumn
code which is required:
Step One Use the ColumnAttribute
to introduce the new column name and then add-migration (e.g. Add-Migration ColumnChanged
)
public class ReportPages{ [Column("Section_Id")] //Section_Id public int Group_Id{get;set}}
Step-Two change the property name and again apply to same migration (e.g. Add-Migration ColumnChanged -force
) in the Package Manager Console
public class ReportPages{ [Column("Section_Id")] //Section_Id public int Section_Id{get;set}}
If you look at the Migration class you can see the automatically code generated is RenameColumn
.
In EF Core, I use the following statements to rename tables and columns:
As for renaming tables:
protected override void Up(MigrationBuilder migrationBuilder) { migrationBuilder.RenameTable(name: "OldTableName", schema: "dbo", newName: "NewTableName", newSchema: "dbo"); } protected override void Down(MigrationBuilder migrationBuilder) { migrationBuilder.RenameTable(name: "NewTableName", schema: "dbo", newName: "OldTableName", newSchema: "dbo"); }
As for renaming columns:
protected override void Up(MigrationBuilder migrationBuilder) { migrationBuilder.RenameColumn(name: "OldColumnName", table: "TableName", newName: "NewColumnName", schema: "dbo"); } protected override void Down(MigrationBuilder migrationBuilder) { migrationBuilder.RenameColumn(name: "NewColumnName", table: "TableName", newName: "OldColumnName", schema: "dbo"); }