Search code examples
c#entity-frameworkentity-framework-corenpgsql

NPGSQL MapEnum fails after EF migration


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.


Solution

  • 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();
        }
    }