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

后端 未结 8 2099
北海茫月
北海茫月 2021-01-30 10:25

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 dat

8条回答
  •  隐瞒了意图╮
    2021-01-30 10:46

    Adding to Josh Gallagher's answer:

    In some places the sp_RENAME syntax is described like this:

    sp_RENAME 'TableName.[OldColumnName]' , '[NewColumnName]', 'COLUMN'
    

    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.

提交回复
热议问题