Skip to content

Seeding database during migration fails when using newly added Enum #3675

@pgolinski

Description

@pgolinski

I have a migration in EF Core 9 (package: Npgsql.EntityFrameworkCore.PostgreSQL 9.0.4) adding new enum type:

   migrationBuilder.AlterDatabase()
      .Annotation("Npgsql:Enum:event_stack_event_status", "closed,new,taken,unknown")

The enum is registered like so:

       services.AddDbContext<DatabaseContext>(options =>
       {
           options.UseNpgsql(
               CreateConnString(variables.DatabaseName),
               npsqlOptions =>
               {
                   npsqlOptions.UseQuerySplittingBehavior(QuerySplittingBehavior.SingleQuery);
                   npsqlOptions.MapEnum<EventStackEventStatus>();
               });
           options.UseDataSeeding();
           options.ConfigureWarnings(c => c.Log((RelationalEventId.CommandExecuted, LogLevel.Debug)));
       }, ServiceLifetime.Transient);

The UseDataSeeding is my extension simply adding seeder implementation:

    public static void UseDataSeeding(this DbContextOptionsBuilder options)
    {
        options.UseSeeding(
            (ctx, storeManagementPerformed) => SeedAsync(ctx, storeManagementPerformed).Wait());

        options.UseAsyncSeeding(SeedAsync);
    }

Migration is applied via migration bundle. During the seed process, where the enum is used, I'm getting error:

System.NotSupportedException: The data type name 'event_stack_event_status' isn't present in your database. You may need to install an extension or upgrade to a newer version.

As far as I know this is an issue with type cache which doesn't contain new enum mapping. I tried to call ReloadTypes in data seeder on current database connection from database context but it changed error to:

System.InvalidCastException: Writing values of 'EventStackEventStatus' is not supported for parameters having DataTypeName 'public.event_stack_event_status'

I'm aware of this issue: #292 and PR that solving it #2951, but it's not applying here because seeder is called during Migrate method before ReloadTypes is called: https://github.com/dotnet/efcore/blob/main/src/EFCore.Relational/Migrations/Internal/Migrator.cs#L192

The only workaround I see right now is to move data seeding to application start. Is there a way to solve it so I can still use data seeding during migration?

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions