Skip to content

Types not being reloaded properly after adding extension and running Migrate() #292

Closed

Description

@kusey

Hi, I have installed the newest Npgsql.EntityFrameworkCore.PostgreSQL package in my project, and I added the 'hstore' extension like this:
modelBuilder.HasPostgresExtension("hstore");
The migration file content generated like this:
migrationBuilder.AlterDatabase().Annotation("Npgsql:PostgresExtension:hstore", "'hstore', '', ''");

After this, I have my own database initialize process in main function:

var host = BuildWebHost(args);

            var serviceProvider = host.Services;
            // initialize database
            using (var scope = serviceProvider.CreateScope())
            {
                var dbContext = scope.ServiceProvider.GetRequiredService<ISDbContext>();
                if (dbContext.Database.GetPendingMigrations().Any())
                {
                    dbContext.Database.Migrate();
                }
                StorageInitializer.Initialize(dbContext, BuilderContext.HostingEnvironment);
            }

I invoke the Migrate() function in order to update my database automatically, after this, I checked that the extension 'hstore' already added to my database, but when I insert records to table(which contains a field with data type Dictionary<string, string>) I got this exception: "NpgsqlException: The PostgreSQL type 'hstore', mapped to NpgsqlDbType 'Hstore' isn't present in your database. You may need to install an extension or upgrade to a newer version."

I'm not sure how to resolve this issue, can anybody help me?
Thanks.

Activity

  1. kusey commented on Feb 2, 2018

    @kusey
    Author

    In addition, if I do not invoke dbContext.Database.Migrate() function explicitly, just use common line: "dotnet ef database update" to update my database, everything is ok when inserting records to database.

  2. roji commented on Feb 2, 2018

    @roji
    Member

    This is probably because after adding the extension in the database, Npgsql (the ADO layer) needs to reload the types to discover the newly-added hstore... This was supposed to be taken care of, but there may be an issue - I'll try to take a look soon.

    The workaround is indeed to run the migration from a different process - if you simply restart your application everything should work fine.

  3. changed the title [-]issue about add extension 'hstore'[/-] [+]Types not being reloaded properly after adding extension in migrations[/+] on Feb 2, 2018
  4. kusey commented on Feb 2, 2018

    @kusey
    Author

    Thanks for your reply.
    If it's a bug I will find some workarounds temporary.

  5. myshon commented on Feb 14, 2018

    @myshon

    I create database in integration test, I use context.Database.Migrate() but it fails with same error. When I added ReloadTypes after database migration and it started working

    using (var ctx = server.Host.Services.GetService<MyContext>())
    using (var conn = new NpgsqlConnection(ctx.Database.GetDbConnection().ConnectionString))
    {
       conn.Open();
       conn.ReloadTypes();
       conn.Close();
    } 
    
  6. roji commented on Feb 27, 2018

    @roji
    Member

    Oops, I ran into this today and fixed it as #313, forgetting that this issue was open.

    Can you please test version 2.0.2-166 from the stable feed and confirm that the problem goes away?

  7. myshon commented on Feb 28, 2018

    @myshon

    Pulled 2.0.2-166 and unfortunetelty still not works, but an error is different, without explicit ReloadTypes I have:

    System.NotSupportedException: The field 'Code' has a type currently unknown to Npgsql (OID 22894). You can retrieve it as a string by marking it as unknown, please see the FAQ

  8. roji commented on Feb 28, 2018

    @roji
    Member

    @myshon what's the type of Code? Any chance you could post a small code sample reproducing the issue? Things seem to work well on my end.

  9. myshon commented on Feb 28, 2018

    @myshon

    @roji I use citext extension:
    modelBuilder.HasPostgresExtension("citext");
    Code has type citext
    builder.Property(x => x.Code).HasColumnType("citext");
    Give me some time, I will try to reproduce it later.

  10. roji commented on Feb 28, 2018

    @roji
    Member

    Great, thanks - a simple small context with some minimal code would be ideal.

  11. kusey commented on Mar 1, 2018

    @kusey
    Author

    @roji I still got the same error using pkg 2.0.2-ci-00166.

  12. roji commented on Mar 1, 2018

    @roji
    Member

    @kusey as I wrote above, a small code sample would be very helpful here. In my scenario it's OK, and I don't know what you're doing differently.

  13. kusey commented on Mar 5, 2018

    @kusey
    Author

    @roji Here is my code, executing pending migrations when website startup:

    var host = BuildWebHost(args);
    var serviceProvider = host.Services;
    // initialize database
    using (var scope = serviceProvider.CreateScope())
    {
        var dbContext = scope.ServiceProvider.GetRequiredService<ISDbContext>();
        if (dbContext.Database.GetPendingMigrations().Any())
        {
            dbContext.Database.Migrate();
        }
        StorageInitializer.Initialize(dbContext);
    }

    and the database initialize code like this:

    if (!dbContext.Set<TStorageModel>().Any())
    {
        dbContext.AddRange(entities);
        dbContext.SaveChanges();
    }

    Sorry for the late reply, i'm going crazy that github always show error message 'You can't comment at this time'.

  14. 34 remaining items

  15. modified the milestones: 8.0.0, Backlog on Nov 16, 2023
  16. changed the title [-]Types not being reloaded properly after adding extension in migrations[/-] [+]Types not being reloaded properly after adding extension and running Migrate()[/+] on Nov 16, 2023
  17. modified the milestones: Backlog, 8.0.0 on Nov 16, 2023
  18. added a commit that references this issue on Nov 16, 2023
    8bbcabb
  19. added a commit that references this issue on Nov 16, 2023
    4cfcd4f
  20. OlegTopalov commented on Nov 28, 2023

    @OlegTopalov

    @roji Will this fix be added to 6.x versions? We are currently not planning to update to 8.x versions

  21. roji commented on Nov 28, 2023

    @roji
    Member

    @OlegTopalov no, that's not planned. Note that it's very easy to work around this - just add ReloadTypes() after calling Migrate() in your code (see above).

  22. umutdr commented on Nov 19, 2024

    @umutdr
    var dbContext = scope.ServiceProvider.GetRequiredService<ISDbContext>();
    if (dbContext.Database.GetPendingMigrations().Any())
    {
        dbContext.Database.Migrate();
    
        dbContext.Database.OpenConnection();
        ((NpgsqlConnection)dbContext.GetDbConnection()).ReloadTypes();
    }

    I was getting a "Can't cast database type . to Point" error when I try to get a geometry data from pgsql database with using entity framework in my .net 7 web api and also getting "The NpgsqlDbType 'Geometry' isn't present in your database. You may need to install an extension or upgrade to a newer version." error when I try to insert a new geometry data (point in this case) pgsql database. I searched for a solution, tried almost everything but nothing worked and then I found this answer (#292 (comment)) in this thread and applied it and it worked! Here is my code.

    var serviceProvider = builder.BuildServiceProvider();
    using (var serviceScope = serviceProvider.CreateScope())
    {
        var unitOfWork = serviceScope.ServiceProvider.GetRequiredService<IUnitOfWork>();
        var dbContext = unitOfWork as DbContext;
    
        dbContext.Database.OpenConnection();
        ((NpgsqlConnection)dbContext.Database.GetDbConnection()).ReloadTypes();
        dbContext.Database.CloseConnection();
    }
  23. mlichtner commented on Nov 24, 2024

    @mlichtner

    Just in case some runs across this, the new data seeding mechanism introduced in EF Core 9 (docs) exposes the same issue mentioned here.
    Same workaround works though. In your seeding code just do something like shown below.
    For me this popped up with a custom enum type, mapped through MapEnum<T>(). Which works fine without the workaround if you skip the seeding call.

    await context.Database.OpenConnectionAsync(cancellationToken);
    await ((NpgsqlConnection)context.Database.GetDbConnection())
        .ReloadTypesAsync(cancellationToken);
    await context.Database.CloseConnectionAsync();
    // actual seeding follows    

    Hope this helps.

  24. added theissue type on Jun 19, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

No labels
No labels

Type

Projects

No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions