I realised that I had spelt one of my column headers incorrectly so I changed it in the model and created a new migration to update it into the database. All worked perfectly until I realised that what actually appeared to happen was a new column replaced the existing column and erased all the data. As it happens, as this was a tutorial database, it was no big deal and a work of a few minutes to put the data back.
How/what do I do to update/rename a column without losing the data in it?
Not sure how this didn't come up in my search but here is a directly related post: Rename table field without losing data, using automatic migrations
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/…
To rename a column in R you can use the rename() function from dplyr. For example, if you want to rename the column “A” to “B”, again, you can run the following code: rename(dataframe, B = A) .
EF Core creates its migrations by comparing your models to the current database snapshot (a c# class). It then uses this to create a migration file you can review. However, EF Core cannot always know if you replaced this column or created a new column. When you check your migration file, make sure there are no column drops, index drops (related to this column) etc. You can replace all these with something like this:
migrationBuilder.RenameColumn(
name: "ColumnA",
table: "MyTable",
newName: "ColumnB");
migrationBuilder.RenameColumn
usually works fine but sometimes you have to handle indexes as well.
migrationBuilder.RenameColumn(name: "Identifier", table: "Questions", newName: "ChangedIdentifier", schema: "dbo");
Example error message when updating database:
Microsoft.Data.SqlClient.SqlException (0x80131904): The index 'IX_Questions_Identifier' is dependent on column 'Identifier'.
The index 'IX_Questions_Identifier' is dependent on column 'Identifier'.
RENAME COLUMN Identifier failed because one or more objects access this column.
In this case you have to do the rename like this:
migrationBuilder.DropIndex(
name: "IX_Questions_Identifier",
table: "Questions");
migrationBuilder.RenameColumn(name: "Identifier", table: "Questions", newName: "ChangedIdentifier", schema: "dbo");
migrationBuilder.CreateIndex(
name: "IX_Questions_ChangedIdentifier",
table: "Questions",
column: "ChangedIdentifier",
unique: true,
filter: "[ChangedIdentifier] IS NOT NULL");
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With