Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can we rename the primary key of a table in FluentMigrator?

I need to rename the primary key of an existing table through FluentMigrator so an automapper can automatically detect the column.

For most columns, it's a simple 1) delete any foreign key constraints on that column 2) delete indices for that column and 3) rename the column. I have historically done this by:

Delete.ForeignKey("foreignkeyconstraint").OnTable("mytable");
Delete.Index("UserId").OnTable("mytable");
Rename.Column("UserId").OnTable("mytable").To("UserInfo_id");

However, this doesn't appear to work for primary keys, since I can't delete the automatically created index on that column. What is the correct way to rename a primary key column with FluentMigrator?

like image 475
Chris Avatar asked Nov 27 '13 22:11

Chris


People also ask

How can I change the primary key name in MySQL column?

You can set primary key on an existing column in MySQL with the help of alter command.

Can we rename primary key column?

In SQL Server, you can use the sp_rename stored procedure to rename a user created object in the current database, including a primary key.

What is Fluentmigrator?

Fluent Migrator is a migration framework for . NET much like Ruby on Rails Migrations. Migrations are a structured way to alter your database schema and are an alternative to creating lots of sql scripts that have to be run manually by every developer involved.


2 Answers

Use the following method call to rename your primary key (SQL Server)

Execute.Sql("EXEC sp_rename N'[Current_Primary_Key_Name]', '[New_Primary_Key_Name]', 'object';");
like image 147
labilbe Avatar answered Nov 15 '22 15:11

labilbe


Something like this should work as long as it is not an identity (auto increment) column as well:

Delete.PrimaryKey("PRIMARY KEY").FromTable("mytable");
like image 33
Daniel Lee Avatar answered Nov 15 '22 17:11

Daniel Lee