NPGSQL MapEnum fails after EF migration

c# entity-framework entity-framework-core npgsql

Question

I added an enum to entity framework and registered it with NPGSQL, as per docs:

static DataContext()
{
    NpgsqlConnection.GlobalTypeMapper.MapEnum<MyEnum>();
}

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
    modelBuilder.ForNpgsqlHasEnum<MyEnum>();
    ...
}

After running migrations and starting up the web application, the following exception is thrown:

The CLR enum type MyEnum must be registered with Npgsql before usage, please refer to the documentation

If I restart the application again, it works just fine - this only occurs immediately after the migration in which MyEnum was added is applied.

1
2
5/2/2019 4:46:24 PM

Accepted Answer

The problem is that NPGSQL's type mapping gets out of sync with the database after migrations occur, and types need to be reloaded after migrations are performed.

This can be rectified by calling ReloadTypes() after calling Migrate():

public void Migrate()
{
    Database.Migrate();

    using (var connection = (NpgsqlConnection)Database.GetDbConnection())
    {
        connection.Open();
        connection.ReloadTypes();
    }
}
3
5/2/2019 4:46:24 PM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow