Skip to content

EF Core continuous migration error with npgsql HiLo #3613

Closed

Description

@merijndejonge

I'm using Hilo with a custom sequence name. When creating migrations, EF Core always creates a migration to drop the sequence with the normal name. Since EF Core 9.0, this produces a runtime exception because EF Core thinks there is are pending model changes (https://learn.microsoft.com/en-us/ef/core/what-is-new/ef-core-9.0/breaking-changes#pending-model-changes).

This is the minimal example:

public class Item
{
    public int Id { get; set; }
}

public class XContext(DbContextOptions<XContext> options) : DbContext(options)
{
    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        const string sequenceName = "EntityFrameworkHiLoSequenceXContext";
        modelBuilder.HasSequence<int>(sequenceName).IncrementsBy(5);
        modelBuilder.UseHiLo(sequenceName);
    }

    public DbSet<Item> Items { get; [UsedImplicitly] init; }
}

Initially, a correct migration script is generated by running dotnet ef migrations add Initial:

namespace Test.Migrations
{
    /// <inheritdoc />
    public partial class Initial : Migration
    {
        /// <inheritdoc />
        protected override void Up(MigrationBuilder migrationBuilder)
        {
            migrationBuilder.CreateSequence<int>(
                name: "EntityFrameworkHiLoSequenceXContext",
                incrementBy: 5);

            migrationBuilder.CreateTable(
                name: "Items",
                columns: table => new
                {
                    Id = table.Column<int>(type: "integer", nullable: false)
                },
                constraints: table =>
                {
                    table.PrimaryKey("PK_Items", x => x.Id);
                });
        }

        /// <inheritdoc />
        protected override void Down(MigrationBuilder migrationBuilder)
        {
            migrationBuilder.DropTable(
                name: "Items");

            migrationBuilder.DropSequence(
                name: "EntityFrameworkHiLoSequenceXContext");
        }
    }
}

Also the generated snapshot is fine (i.e., only the sequence with my name is present

// <auto-generated />
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
using Test;
using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata;

#nullable disable

namespace Test.Migrations
{
    [DbContext(typeof(XContext))]
    partial class XContextModelSnapshot : ModelSnapshot
    {
        protected override void BuildModel(ModelBuilder modelBuilder)
        {
#pragma warning disable 612, 618
            modelBuilder
                .HasAnnotation("ProductVersion", "9.0.8")
                .HasAnnotation("Relational:MaxIdentifierLength", 63);

            NpgsqlModelBuilderExtensions.UseHiLo(modelBuilder, "EntityFrameworkHiLoSequenceXContext");

            modelBuilder.HasSequence<int>("EntityFrameworkHiLoSequenceXContext")
                .IncrementsBy(5);

            modelBuilder.Entity("Test.Item", b =>
                {
                    b.Property<int>("Id")
                        .ValueGeneratedOnAdd()
                        .HasColumnType("integer");

                    NpgsqlPropertyBuilderExtensions.UseHiLo(b.Property<int>("Id"));

                    b.HasKey("Id");

                    b.ToTable("Items");
                });
#pragma warning restore 612, 618
        }
    }
}

But now, when I run dotnet ef migrations add NoChanges1, EF Core creates another migration to drop the sequence with the default name (EntityFrameworkHiLoSequence):

namespace Test.Migrations
{
    /// <inheritdoc />
    public partial class NoChanges1 : Migration
    {
        /// <inheritdoc />
        protected override void Up(MigrationBuilder migrationBuilder)
        {
            migrationBuilder.DropSequence(
                name: "EntityFrameworkHiLoSequence");
        }

        /// <inheritdoc />
        protected override void Down(MigrationBuilder migrationBuilder)
        {
            migrationBuilder.CreateSequence(
                name: "EntityFrameworkHiLoSequence",
                incrementBy: 10);
        }
    }
}

The resulting snapshot is exactly the same as the initial one.
Each time I run dotnet ef migrations add ... I get a new migration that is exactly the same as the previous one.

Somehow, EF Core gets confused and doesn't see that there are now pending model changes.

I'm using

  • Npgsql.EntityFrameworkCore.PostgreSQL version 9.0.4
  • Microsoft.EntityFrameworkCore version 9.0.8

Activity

  1. merijndejonge commented on Oct 27, 2025

    @merijndejonge
    Author

    Anyone who can look at this plz?

  2. asukhinin commented on Dec 22, 2025

    @asukhinin

    Npgsql.EntityFrameworkCore.PostgreSQL 10.0.0 is also affected by this issue.

  3. merijndejonge commented on Feb 24, 2026

    @merijndejonge
    Author

    Why is nobody looking at this??

  4. NinoFloris commented on Feb 24, 2026

    @NinoFloris
    Member

    Efcore.pg is maintained by @roji in his free time. In fact most EF core providers are a volunteer based open source effort. HiLo is a niche feature, relatively speaking, so I'm assuming he'll get to this issue in due time.

  5. added theissue type on Oct 18, 2026
  6. roji commented on Oct 18, 2026

    @roji
    Member

    AI Triage

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

    Confirmed bug in Npgsql's provider-specific snapshot generation. The reported model also produces the same spurious DropSequence("EntityFrameworkHiLoSequence") migration with SQL Server, whose separate provider-specific generator contains equivalent logic. These can be fixed independently: this issue should remain open for the Npgsql fix, and the corresponding SQL Server bug is tracked in dotnet/efcore#39324. My earlier recommendation to close this issue in favor of an upstream issue was incorrect.

    Reproduction and versions

    I reproduced the original model, including its explicitly declared int sequence and increment of 5:

    Provider Provider version EF Core version Result
    Npgsql 8.0.0 8.0.0 Spurious default-sequence drop; pending model changes
    Npgsql 8.0.11 8.0.32 Same
    Npgsql 9.0.4 9.0.8 Same
    Npgsql 10.0.3 10.0.13 Same
    SQL Server 9.0.8 9.0.8 Same

    The reduced repro below needs only modelBuilder.UseHiLo("EntityFrameworkHiLoSequenceXContext"); neither HasSequence<int>() nor the custom increment is necessary. I also reproduced this reduced case with SQL Server 10.0.13 and Npgsql 9.0.4 / EF Core 9.0.8.

    On SQL Server 9.0.8, adding two successive migrations without changing the model produced the same default-sequence drop each time. HasPendingModelChanges() remained true, and dotnet ef database update threw PendingModelChangesWarning before attempting a database connection.

    Regression assessment: The underlying snapshot mismatch is already present in the original 8.0.0 release, so it was not introduced by upgrading from EF Core 8 to 9. EF Core 9's new pending-model validation makes the existing mismatch fail when applying migrations, as described in dotnet/efcore#33732. No last-known-good release was identified among the versions tested.

    Cause

    The snapshot is not actually equivalent to the configured model. Although its explicit HasSequence(...) declaration names only the custom sequence, it also contains:

    SqlServerModelBuilderExtensions.UseHiLo(modelBuilder, "EntityFrameworkHiLoSequenceXContext");
    // Inside the Item configuration:
    SqlServerPropertyBuilderExtensions.UseHiLo(b.Property<int>("Id"));

    The parameterless property-level call does not inherit the model's custom sequence name: it selects EntityFrameworkHiLoSequence and adds that sequence to the snapshot model. That creates a sequence absent from the application's model, so the next model comparison generates its removal. Re-scaffolding writes the same problematic property call, repeating the cycle.

    This behavior is visible in both the SQL Server property extension and the Npgsql property extension. Snapshot generation needs to preserve the effective custom sequence rather than reconstructing a property configured against the default sequence.

    minimal repro

    Use this standalone console project with dotnet-ef 9.0.8. No running database is required to reproduce the migration or pending-model detection.

    HiLoRepro.csproj:

    <Project Sdk="Microsoft.NET.Sdk">
      <PropertyGroup>
        <OutputType>Exe</OutputType>
        <TargetFramework>net8.0</TargetFramework>
        <ImplicitUsings>enable</ImplicitUsings>
        <Nullable>enable</Nullable>
      </PropertyGroup>
      <ItemGroup>
        <PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer" Version="9.0.8" />
        <PackageReference Include="Microsoft.EntityFrameworkCore.Design" Version="9.0.8" />
      </ItemGroup>
    </Project>

    Program.cs:

    using Microsoft.EntityFrameworkCore;
    using Microsoft.Extensions.Logging;
    
    await using var context = new XContext();
    Console.WriteLine(context.Database.HasPendingModelChanges());
    
    public class XContext : DbContext
    {
        public DbSet<Item> Items { get; set; }
    
        protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
            => optionsBuilder
                .UseSqlServer("Server=localhost;Database=HiLoRepro;Integrated Security=true;TrustServerCertificate=true")
                .LogTo(Console.WriteLine, LogLevel.Information)
                .EnableSensitiveDataLogging();
    
        protected override void OnModelCreating(ModelBuilder modelBuilder)
            => modelBuilder.UseHiLo("EntityFrameworkHiLoSequenceXContext");
    }
    
    public class Item
    {
        public int Id { get; set; }
    }

    Run:

    dotnet ef migrations add Initial
    dotnet ef migrations add NoChanges1
    dotnet run
    dotnet ef migrations add NoChanges2

    Expected: NoChanges1 and NoChanges2 are empty, and the program prints False.

    Actual: the program prints True, and both migrations contain:

    protected override void Up(MigrationBuilder migrationBuilder)
    {
        migrationBuilder.DropSequence(
            name: "EntityFrameworkHiLoSequence");
    }
    
    protected override void Down(MigrationBuilder migrationBuilder)
    {
        migrationBuilder.CreateSequence(
            name: "EntityFrameworkHiLoSequence",
            incrementBy: 10);
    }

    Related issues

    I found no exact duplicate in the open or closed EF Core issues searched. The closest related reports are dotnet/efcore#28223, another repeated HiLo sequence-drop issue involving default-schema lookup, and dotnet/efcore#26134, an older HiLo snapshot-generation failure involving the wrong extension class. Neither appears to describe this exact case: the repro here has no default schema and generates compilable snapshots.

  7. added this to the 10.0.4 milestone on Oct 18, 2026
  8. self-assigned this
    on Oct 19, 2026
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