Search code examples
postgresqlentity-framework-coreef-code-first

ALTER TYPE ... ADD cannot run inside a transaction block - Entity Framework


I'm getting an error when trying to run migrations to a PostGres database when I'm adding an enum. I'm using Dotnet5 and Entity Framework

ALTER TYPE ethnicity_enum ADD VALUE 'hi'; Npgsql.PostgresException (0x80004005): 25001: ALTER TYPE ... ADD cannot run inside a transaction block

Here's the migration that is created:

 protected override void Up(MigrationBuilder migrationBuilder)
    {
        migrationBuilder.AlterDatabase()
            .Annotation("Npgsql:Enum:patient_ethnicity_enum", "afna,hi")
            .OldAnnotation("Npgsql:Enum:patient_ethnicity_enum", "afna");

    }

    protected override void Down(MigrationBuilder migrationBuilder)
    {
        migrationBuilder.AlterDatabase()
            .Annotation("Npgsql:Enum:patient_ethnicity_enum",
                "afna")
            .OldAnnotation("Npgsql:Enum:patient_ethnicity_enum",
                "afna,hi");
    }

Any ideas how to solve this?


Solution

  • Following a comment from Adrian, I found you can do it this way.

      migrationBuilder.Sql("ALTER TYPE patient_ethnicity_enum ADD VALUE 'hi'", true);
      migrationBuilder.AlterDatabase();
    

    The "true" parameter is for suppressing the transaction.

    This works but It's not ideal as rolling the migration back could potentially cause massive issues on live data.