How to rename a database column in Entity Framework 5 Code First migrations without losing data?
Manually edit the Up and Down methods of the migration to use the RenameColumn
method to replace the AddColumn
and DropColumn
that it automatically generates for you.
As already said, replace the AddColumn
and DropColumn
that is automatically generated with RenameColumn
.
Example:
namespace MyProject.Model.Migrations
{
using System;
using System.Data.Entity.Migrations;
public partial class RenameMyColumn : DbMigration
{
public override void Up()
{
// Remove the following auto-generated lines
AddColumn("dbo.MyTable", "NewColumn", c => c.String(nullable: false, maxLength: 50));
DropColumn("dbo.MyTable", "OldColumn");
// Add this line
RenameColumn("dbo.MyTable", "OldColumn", "NewColumn");
}
public override void Down()
{
// Remove the following auto-generated lines
AddColumn("dbo.MyTable", "OldColumn", c => c.String(nullable: false, maxLength: 50));
DropColumn("dbo.MyTable", "NewColumn");
// Add this line
RenameColumn("dbo.MyTable", "NewColumn", "OldColumn");
}
}
}
You can get the migration to call RenameColumn
for you if you do this:
[Column("NewName")]
public string OldName { get; set; }
Here is the generated migration:
public override void Up()
{
RenameColumn(table: "Schema.MyTable", name: "OldName", newName: "NewName");
}
public override void Down()
{
RenameColumn(table: "Schema.MyTable", name: "NewName", newName: "OldName");
}
If you want your property and DB column to be the same name, you can rename the property later and remove the Column
attribute.