Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

EF Migrations: RenameColumn in Automatic Migrations?

If you rename a property, the Visual Studio IDE is smart enough to help you refactor to rename that property throughout your code. If that rename is on a model used in EF Migrations, and you run a standard automatic migration like:

update-database -f

You'll get this:

AddColumn("NewName"...
DropColumn("OldName"...

Not what you wanted. Obviously running Add-Migration at this point will let you go in and manually change these 2 calls to a single call to RenameColumn, but is there some way to get Automatic Migrations to do this automatically? Some approach to property rename that I'm not doing right, perhaps?

I'm using EF 5.0 in VS2012, but this behavior appears in EF 4.3.1 and VS2010 as well.

like image 480
Chris Moschini Avatar asked Sep 10 '12 16:09

Chris Moschini


People also ask

How do I turn on automatic migration in Entity Framework?

Open the Package Manager Console from Tools → Library Package Manager → Package Manager Console and then run the enable-migrations –EnableAutomaticMigration:$true command (make sure that the default project is the project where your context class is).


2 Answers

Migrations can’t automatically detect the rename of a property and column. The scaffolded migration will contain a Drop/Create that you’ll need to change into a Rename.

If you just rename the column (by adding a [Column] annotation to the property) we can detect that as a rename because we can match on the name of the property the column is mapped to.

We did consider adding a –Renames switch to the Add-Migration command, but in the end we decided editing the generated code was easier than working out the syntax for supplying renames at the command line.

~Rowan

like image 148
Rowan Miller Avatar answered Nov 22 '22 10:11

Rowan Miller


My opinion: EF has no idea that that you have renamed existing column. Refactoring is design time change without any persisted information about the change so when you run migrations, EF simply don't know how to differ between renaming and real deletion/adding of a new column.

like image 40
Ladislav Mrnka Avatar answered Nov 22 '22 11:11

Ladislav Mrnka