Home > Mobile >  How do I drop a column and create a new one instead of renaming in EF Core?
How do I drop a column and create a new one instead of renaming in EF Core?

Time:10-15

Trying to delete two columns and add a new column (no relationship between deleted and new) in one of my models but the generated migration renames one of the deleted column instead. Since the deleted columns hold data in production, they must be dropped instead of renamed.

Is there a way to fix this so the generated migration drops and create instead of renaming?

Variables in model:

public DateTime? PublishedAt { get; private set; }
public bool? IsValidated { get; private set; }
public States? States { get; private set; } // Added
public Invites? Invites { get; private set; } // Removed
public string Info { get; private set; } // Removed

Generated migration:

protected override void Up(MigrationBuilder migrationBuilder)
{
    migrationBuilder.DropColumn(
        name: "Info",
        table: "Articles");

    migrationBuilder.RenameColumn(
        name: "Invites",
        table: "Articles",
        newName: "States");
}

CodePudding user response:

Sometimes EF can think you want to rename a column, as opposed to creating a column if the types are the same.

It's not an exact science so either create a migration to first delete the column, apply, then create another to add a new one so EF picks up on them as separate operations, or I would just change the migration manually.

In case of the latter option, use the MigrationBuilder.AddColumn method to add the States column & then change RenameColumn to DropColumn and drop Invites:

protected override void Up(MigrationBuilder migrationBuilder)
{
    migrationBuilder.DropColumn(
        name: "Info",
        table: "Articles");

    migrationBuilder.DropColumn(
        name: "Invites",
        table: "Articles");

    migrationBuilder.AddColumn(
        name: "States",
        table: "Articles");
}

In case you ever want to revert the migration, remember to also change the Down(MigrationBuilder migrationBuilder) method so that it carries out the reverse of your updated Up(...) method, not the old one:

protected override void Down(MigrationBuilder migrationBuilder)
{
    migrationBuilder.AddColumn(
        name: "Info",
        table: "Articles");

    migrationBuilder.AddColumn(
        name: "Invites",
        table: "Articles");

    migrationBuilder.DropColumn(
        name: "States",
        table: "Articles");
}
  • Related