EF Core can remove important data if you are not careful. Read how you can prevent your migration losing data when renaming columns.
If you rename a field in your model, EF Core has trouble determining your intent. When you create a migration, it will remove the old field (and all its data) and add one with the new name instead of just renaming the existing field. If you applied this migration without checking you can lose an important chunk of your database!
Here’s an example. Lets rename the Customers.Name field to Customers.FullName. If we get EF Core to generate a new migration and examine the code we will see this:
migrationBuilder.DropColumn(
name: "Name",
table: "Customers");
migrationBuilder.AddColumn<string>(
name: "FullName",
table: "Customers",
nullable: true);
If we applied the migration as is, all the customer names would be lost!
The migration generation process should warn us about the data-loss but its far too easy to miss.
Fortunately we can edit the migration to prevent the data being lost. We need to replace the two commands with a single RenameColumn command:
migrationBuilder.RenameColumn(
name: "Name",
table: "Customers",
newName: "FullName");
Now, if we apply the migration to a database, the customer data will not be lost.