Skip to content

context.Database.Migrate() cannot create database #3701

Closed as duplicate
Closed as duplicate

Description

@zhaozehong

I am working with the latest .NET. using Visual Studio 2026.
Image
In my application, I would like to support several database provider, including PostgreSQL.

I can do Add-Migration.
Image

But, it cannot create database when I call context.DatabaseMigrate() in the source for postgreSQL, which works for all other database provider(I tested it with LocalDB, SQLServer, SQLite). Then I changed the server name from localhost to 127.0.0.1 as suggested, nothing changed.
Image

Next, I manually called Update-Database after Add-Migration operation in Package Manager Console, it works, the database really created. And all tables, including __EFMigrationsHistory, are created there.
Image
there is an error line in the picture but the database really created.

Next I put code to set default schema to public.
Image
then call Update-Database again(I have dropped the database created on last step), this time it failed.
Image

Ok, let's continue with last database created step.
After database created with Update-Database, I run my application, when it goes to context.Database.Migrate(), it show me
Image
I know 100% that there is no pending migration.(I called Update-Database, and there is only one migration existing and it must have been applied when Update-Database is called).
To verify,
Image

the pendingMigrations really has nothing.
I can jump context.Database.Migrate() to avoid the error message popup in the way shown in above picture.

Then I made another try,

  1. I create an empty database with pgAdmin (like customer do)
    Image
  2. I run the application, and the application will call context.Database.Migrate()
    Image
  3. I checked the Tables, nothing inside
    Image

NOTE:
context.Database.EnsureCreated() can always create database.
The problem for me is that, context.Database.Migrate() call doesn't really create the database. But I need to create database in this way.

Activity

  1. added theissue type on Oct 17, 2026
  2. roji commented on Oct 17, 2026

    @roji
    Member

    AI Triage

    The below is an AI-generated analysis and may contain inaccuracies.

    The screenshots show RelationalEventId.PendingModelChangesWarning, rather than a failure to execute CREATE DATABASE. This means EF detected a difference between the current model and the last migration's model snapshot.

    Findings

    • With the reported Npgsql provider 10.0.0 and EF Core 10.0.1, a minimal console application successfully creates a missing PostgreSQL database and applies its initial migration through context.Database.Migrate(). Tested against PostgreSQL 18.4.
    • Adding HasDefaultSchema("public") after generating the migration reproduces the exception shown in the report. Generating another migration with that configuration resolves it. Although public is PostgreSQL's usual default schema, explicitly configuring it changes EF's model metadata.
    • After applying the initial migration, the failing example has zero pending migrations but pending model changes. GetPendingMigrations() checks which existing migrations have not been applied; it does not check whether the current model matches the snapshot. Database.HasPendingModelChanges() checks the latter.
    • Model validation happens before database creation in EF Core's migrator. I also confirmed that a model/snapshot mismatch prevents creation of a missing database. Creating the database manually does not resolve that mismatch.
    • SQLite also throws the same exception when a property is added without generating a migration. This validation is not PostgreSQL-specific. SQL Server was not available for comparison.
    • The initial connection-error log line also appears in the successful PostgreSQL database-creation run, while checking migration history against the not-yet-existing database. That line alone does not establish that migration failed.

    Version comparison: The matching-model case succeeds, and the model-drift case throws, on Npgsql 10.0.0 / EF 10.0.0, the reported Npgsql 10.0.0 / EF 10.0.1, and Npgsql 10.0.3 / EF 10.0.13. SQLite has the same model-drift behavior on EF 10.0.0, 10.0.1, and 10.0.13. No 10.0.1 regression or provider database-creation defect was established. This validation was introduced intentionally in EF Core 9; see dotnet/efcore#33732.

    What remains unknown: The report does not include the context configuration, model, or snapshot, so I cannot identify why the original runtime model differs before the explicit-schema change. The example below reproduces the validation mechanism, not an unexplained false positive in the original application.

    Please provide a small runnable project containing PostgreContext, its runtime and design-time configuration, and the generated migration/snapshot. As a diagnostic, scaffold an additional migration against the same configuration used at runtime and inspect its contents. In particular, check configuration differences between the application's context and the one created by the tools, and ensure each provider uses its own matching migrations/snapshot. EnsureCreated() bypasses migrations and snapshot validation, so its success does not rule out this problem.

    The evidence currently points to shared EF Core model validation rather than an Npgsql-specific defect. If a reduced project still throws with a genuinely matching snapshot, the recommendation is to open it on dotnet/efcore and close this provider issue in favor of that report, unless it demonstrates PostgreSQL-specific behavior.

    minimal repro

    This SQLite fallback demonstrates the provider-independent validation. Use a .NET 10 console project with Microsoft.EntityFrameworkCore.Sqlite and Microsoft.EntityFrameworkCore.Design, both version 10.0.1, and the EF CLI tool version 10.0.1.

    Replace Program.cs with:

    using Microsoft.EntityFrameworkCore;
    using Microsoft.Extensions.Logging;
    
    using var context = new TestContext();
    Console.WriteLine($"Pending migrations: {context.Database.GetPendingMigrations().Count()}");
    Console.WriteLine($"Pending model changes: {context.Database.HasPendingModelChanges()}");
    context.Database.Migrate();
    
    public class TestContext : DbContext
    {
        public DbSet<Blog> Blogs => Set<Blog>();
    
        protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
            => optionsBuilder
                .UseSqlite("Data Source=repro.db")
                .LogTo(Console.WriteLine, LogLevel.Information)
                .EnableSensitiveDataLogging();
    
        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            if (Environment.GetEnvironmentVariable("ADD_PROPERTY") == "1")
            {
                modelBuilder.Entity<Blog>().Property<string>("Name");
            }
        }
    }
    
    public class Blog
    {
        public int Id { get; set; }
    }

    With ADD_PROPERTY unset, generate and apply the initial migration:

    dotnet ef migrations add Initial
    dotnet run

    Then, in PowerShell:

    $env:ADD_PROPERTY = "1"
    dotnet run

    The second run reports Pending migrations: 0 and Pending model changes: True, then throws PendingModelChangesWarning. No database deletion or recreation is needed.

    Related reports

    These are related candidates, not confirmed duplicates of the original application's unidentified mismatch.

  3. roji commented on Oct 17, 2026

    @roji
    Member

    @zhaozehong please check out dotnet/efcore#35285 for guidance on "pending model changes" and possible issues that could lead to it. If you suspect an actual issue that's specific to the PostgreSQL provider, I'll need to be able to reproduce the problem via a repro.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions