In EF Core 10, renaming Car.Plate to LicensePlate while also shortening its max length scaffolds DropColumn and AddColumn; why, and how do you fix the migration?
answer
- the differ pairs old and new columns
- same name, same property, or same shape
- store type, nullability, length, default compared
- may result in the loss of data
- RenameColumn, then AlterColumn
basics
~20 sEF Core pairs old and new columns only by name, property name or identical shape; a rename plus a length change matches none, so it drops and adds. Rewrite Up as RenameColumn plus AlterColumn and mirror it in Down.
solid answer
~50 sWhen `migrations add` diffs a table, the differ pairs old and new columns in passes: same column name, then same property name, then identical shape (store type, nullability, max length, precision, default and the like). A pure rename keeps the shape, so it pairs and scaffolds `RenameColumn`. Renaming `Plate` to `LicensePlate` and changing `HasMaxLength(20)` to `10` in the same change matches no pass, so you get `DropColumn` plus `AddColumn` and the warning that an operation may result in the loss of data; applied as is, every plate number is gone. Fix it by replacing those two calls with `RenameColumn` followed by `AlterColumn`, and write `Down` as the mirror image. Splitting the work into a rename-only migration and a second one for the length avoids the problem, and `migrationBuilder.Sql` handles any data clean-up the shorter length needs.
code
csharp · 24 linespublic partial class RenamePlateToLicensePlate : Migration
{
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.RenameColumn(name: "Plate", table: "Cars", newName: "LicensePlate");
migrationBuilder.AlterColumn<string>(
name: "LicensePlate", table: "Cars",
type: "character varying(10)", maxLength: 10, nullable: false,
oldClrType: typeof(string),
oldType: "character varying(20)", oldMaxLength: 20);
}
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.AlterColumn<string>(
name: "LicensePlate", table: "Cars",
type: "character varying(20)", maxLength: 20, nullable: false,
oldClrType: typeof(string),
oldType: "character varying(10)", oldMaxLength: 10);
migrationBuilder.RenameColumn(name: "LicensePlate", table: "Cars", newName: "Plate");
}
}go deeper
Recall that a renamed property can come out as a drop and an add, and that the data-loss warning means the migration must be read before it is applied.
Explain how the differ pairs columns by name, property name or identical shape, and write RenameColumn plus AlterColumn with a matching Down.
Show the production habit: split renames from shape changes, order data transformations with migrationBuilder.Sql, and keep Down able to restore data or fail loudly when it cannot.
Set the review gate for destructive operations and decide when a rename needs an expand and contract plan because old and new application versions share the schema.
## How EF Core decides a column was renamed `dotnet ef migrations add` compares the model snapshot with the current model. For each table it must decide which old column corresponds to which new one. Columns it pairs are **diffed** (a different name becomes `RenameColumn`, a different type becomes `AlterColumn`); old columns left unpaired are **dropped**, new ones left unpaired are **added**. The EF Core 10 differ pairs columns in passes, each one only over the columns still unpaired: 1. same column name; 2. same mapped property name on the same entity type; 3. same property name on any entity type mapped to the table; 4. identical column **shape** and the same property name; 5. identical shape and identical column annotations; 6. identical shape and the same annotation names; 7. identical shape alone. **Shape** means the store type, nullability, max length, precision, scale, Unicode and fixed-length settings, collation, comment, default value or default SQL, computed SQL, and the row-version flag. So a **pure rename** (property `Plate` becomes `LicensePlate`, column follows, nothing else changes) is paired by shape and scaffolds `RenameColumn`. A rename **combined with a shape change** is not paired by any pass. ## The car-rental case `Car.Plate` was `character varying(20)` on PostgreSQL. The change renames it and adds `HasMaxLength(10)`: - the names differ, so passes 1 to 4 miss; - the store type differs (`character varying(10)` vs `(20)`), so passes 5 to 7 miss; - the old column is dropped and a new one added. The scaffolder warns: *An operation was scaffolded that may result in the loss of data. Please review the migration for accuracy.* Applied unchanged, the migration deletes every plate number and creates an empty column. ## Fixing the migration Replace the generated `DropColumn` and `AddColumn` with operations that keep the data: - `migrationBuilder.RenameColumn(name: "Plate", table: "Cars", newName: "LicensePlate")`; - `migrationBuilder.AlterColumn<string>(...)` with the new length and the old one in `oldMaxLength` and `oldType`; - in `Down`, the same two steps reversed: alter the length back, then rename back. Alternatives that avoid hand-editing: - **Split the change.** Rename only, scaffold (you get `RenameColumn`), then change the length and scaffold again (you get `AlterColumn`). - **Keep the column name.** If only the C# name should change, map the property to the old column with `HasColumnName("Plate")`; the model's column is unchanged, so nothing is scaffolded. ## When the data itself must change A shorter column can fail or need a data fix first, depending on the provider and the existing values. When the new values must be computed from the old ones, write the steps in order and use raw SQL for the transformation: 1. add the new column as nullable; 2. fill it with `migrationBuilder.Sql(...)`, for example an `UPDATE` that normalises plate numbers; 3. make it required with `AlterColumn`; 4. drop the old column. Rules for that SQL: - it runs inside the migration's transaction unless you pass `suppressTransaction: true`; - it is provider-specific, so branch on `migrationBuilder.ActiveProvider` (or `migrationBuilder.IsNpgsql()`) if the app supports several databases; - never use the `DbContext` or entity classes inside a migration, because historical migrations must compile and behave the same after those types change. ## Review habits that catch this | Signal | What it usually means | |---|---| | The data-loss warning after `migrations add` | A drop that may be a rename in disguise | | `DropColumn` and `AddColumn` on the same table in one `Up` | A rename combined with another change | | Several columns renamed at once with the same shape | The pairing may not match your intent; check each `RenameColumn` | | A hand-edited `Up` with the scaffolded `Down` left alone | `Down` still drops and adds, so a revert loses data | The EF Core docs say a property rename comes out as a drop and an add; the 10.0 differ pairs same-shaped columns, so in practice the drop and add appear when the rename travels with another change. ## Renames the application can see A renamed column is also a contract change for any code reading the table: reports, other services, raw SQL in the app. On a single deploy with downtime, `RenameColumn` is enough. When old and new versions of the app run side by side during a rollout, the rename usually becomes several migrations: add the new column, copy and keep both in sync, switch readers, and drop the old column in a later release. Each step is still an ordinary EF Core migration, scaffolded and then reviewed.
- How do you rename the C# property but keep the database column named Plate?Map the property to the old column, with `HasColumnName("Plate")` in the entity configuration or `[Column("Plate")]` on the property. The model's column is unchanged, so the next `migrations add` scaffolds no operation for it, and queries keep reading `Plate`.
- Why must the data fix in a migration use migrationBuilder.Sql instead of the RentalDbContext?A migration is code that must run the same way years later. Entity classes and the context evolve, so a migration using them breaks or changes behaviour once a property is renamed or removed. SQL inside `migrationBuilder.Sql` is fixed when the migration is written; branch on `migrationBuilder.ActiveProvider` when several providers are supported.
- EF Core always scaffolds RenameColumn whenever a property is renamed.
- EF Core can never detect a rename, so every rename becomes a drop and an add.
- The data-loss warning only appears when the migration is applied to a database.
- After rewriting Up by hand, the scaffolded Down can be left as it is.
- Moving data inside a migration through the DbContext is safer than raw SQL.