Search code examples
c#entity-framework-coremigration

Entity Framework Core fails to rename database column


Whenever I modify one of my entities and generate a migration using Add-Migration <name> in the Package Manager Console, if the generated MigrationBuilder contains a rename column operation such as:

protected override void Up(MigrationBuilder migrationBuilder)
{
    migrationBuilder.RenameColumn(
        name: "OldName",
        table: "MyTable",
        newName: "NewName");
}

then the Update-Database operation fails with the following error:

Object reference not set to an instance of an object.

Applying migration '20230506191317_mymigration'. System.NullReferenceException: Object reference not set to an instance of an object.

at MySql.EntityFrameworkCore.Migrations.MySQLMigrationsSqlGenerator.Generate(RenameColumnOperation operation, IModel model, MigrationCommandListBuilder builder)
at Microsoft.EntityFrameworkCore.Migrations.MigrationsSqlGenerator.<>c.<.cctor>b__82_22(MigrationsSqlGenerator g, MigrationOperation o, IModel m, MigrationCommandListBuilder b)
at [...]
at Microsoft.EntityFrameworkCore.Design.OperationExecutor.OperationBase.Execute(Action action)

It only happens when renaming columns. Removing that command from the migration and running the migration works. The ModelSnapshot is not out of sync.

I either have to nuke my migrations and start fresh or run the migration without the rename and manually rename the table in MySQL workbench.

I'm using .Net 7.0 and Entity Framework Core 7.0.5 with MySQL.

Any ideas? Thanks.


Solution

  • I saw from this question that MySql.EntityFramework.Core has some issues, and to switch to Pomelo. I tried that, also specifying the right MySqlServerVersion version in the options when calling UseMySql and it now works. It also fixed other issues I was running into.