Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to rename a database column in Entity Framework 5 Code First migrations without losing data?

I got the default ASP.NET MVC 4 template successfully running with EF 5.0 Code First Migrations. However, when I update a model property name, the corresponding table column data is dropped by EF 5.0.

Is it somehow possible to rename the table column without dropping data in an automated way?

like image 227
Dante Avatar asked Oct 27 '12 22:10

Dante


People also ask

How do I rename a column in Entity Framework first?

For EF core you can use like this, migrationBuilder. RenameColumn(name: "oldname",table: "tablename",newName: "newname",schema: "schema"); docs.microsoft.com/en-us/dotnet/api/…


2 Answers

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.

like image 99
Josh Gallagher Avatar answered Oct 05 '22 12:10

Josh Gallagher


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");         }     } } 
like image 41
Zanon Avatar answered Oct 05 '22 14:10

Zanon