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?
You can get the migration to call
RenameColumn
for you if you do this:Here is the generated migration:
If you want your property and DB column to be the same name, you can rename the property later and remove the
Column
attribute.like +Josh Gallagher said, you can use up() for doing things like:
i've found this a good help in gettin into migration ;)
Manually edit the Up and Down methods of the migration to use the
RenameColumn
method to replace theAddColumn
andDropColumn
that it automatically generates for you.you have 2 steps to rename column in code first migration
The second step,
add-migration yournamechange command in order to create a partial class DbMigration.
add into up and down method here
RenameColumn("yourDatabase","name","newName");
Because when you connect, your database and model class will communicate via name_column at database and name_type at property method in model above.
Adding to Josh Gallagher's answer:
In some places the sp_RENAME syntax is described like this:
However, that will actually include the brackets in the new column name.
DbMigration's RenameColumn() method will probably do the same, so avoid using brackets when specifying the new column name.
Also, the auto-generated commands in Up() & Down() include DropPrimaryKey() and AddPrimaryKey() if the column being renamed is part of the primary key. These are not needed when using RenameColumn(). The underlying sp_RENAME automatically updates the primary key if needed.
As already said, replace the
AddColumn
andDropColumn
that is automatically generated withRenameColumn
.Example: