Skip to content

Repeated UpdateData for List<string> property with HasData and migrations #3635

Closed

Description

@Varorbc

Bug description

When using EF Core's HasData to seed data for an entity that contains a List property, every time I run Add-Migration, even if nothing has changed in the entity or the seed data, EF Core generates UpdateData statements for the List field.

Your code

await using var context = new BlogContext();
await context.Database.EnsureDeletedAsync();
await context.Database.EnsureCreatedAsync();

public class BlogContext : DbContext
{
    public DbSet<MyEntity> MyEntities { get; set; }

    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
        => optionsBuilder
            .UseNpgsql("Host=localhost;Username=test;Password=test")
            .LogTo(Console.WriteLine, LogLevel.Information)
            .EnableSensitiveDataLogging();

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder.Entity<MyEntity>().HasData(
                new MyEntity
                {
                    Id = 1,
                    Tags = new List<string> { "A", "B", "C" }
                }
            );
    }
}

public class MyEntity
{
    public int Id { get; set; }
    public List<string> Tags { get; set; }
}

EF Core version

9.0.4

Database provider

Npgsql.EntityFrameworkCore.PostgreSQL

Target framework

.NET 9.0

Operating system

Windows 11

IDE

Visual Studio 2022 17.4

Activity

  1. roji commented on Oct 11, 2025

    @roji
    Member

    Thanks @Varorbc, I can see this happening now - will investigate.

  2. added theissue type on Oct 11, 2025
  3. zlepper commented on Dec 1, 2025

    @zlepper

    As a workaround, i have done this in OnModelCreating:

        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            base.OnModelCreating(modelBuilder);
    
            AddManualListComparer<int>(modelBuilder);
            AddManualListComparer<string>(modelBuilder);
            AddManualListComparer<long>(modelBuilder);
        }
    
        private static void AddManualListComparer<TElement>(ModelBuilder modelBuilder)
        {
            foreach (var type in modelBuilder.Model.GetEntityTypes())
            {
                foreach (var property in type.GetProperties())
                {
                    // Fix Npgsql bug #3635: List<int> primitive collections have broken ValueComparer
                    // https://github.com/npgsql/efcore.pg/issues/3635
                    if (property.ClrType == typeof(List<TElement>) && property.IsPrimitiveCollection)
                    {
                        property.SetValueComparer(
                            new ValueComparer<List<TElement>>(
                                (c1, c2) =>
                                    (c1 == null && c2 == null)
                                    || (c1 != null && c2 != null && c1.SequenceEqual(c2)),
                                c => c == null ? 0 : c.Aggregate(0, (a, v) => HashCode.Combine(a, v)),
                                c => c == null ? null! : c.ToList()
                            )
                        );
                    }
                }
            }
        }

    It's a bit of a brute-force solution, but it at least prevents the extra migration changes :)

  4. roji commented on Oct 18, 2026

    @roji
    Member

    AI Triage

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

    Confirmed as an Npgsql-specific bug, with a regression boundary between 6.x and 7.0.0, rather than a new regression in 9.0.4. The issue remains classified as Bug.

    With Npgsql/EF 9.0.4, scaffolding an initial migration and then two more migrations without changing the model or seed data produces the same UpdateData in both subsequent migrations, in both Up and Down. Comparing two independently built, identical models also reproduces this directly through IMigrationsModelDiffer; no database connection, database creation, or data insertion is required.

    Version and provider comparison

    Representative results from the standalone model-differ repro:

    Provider Provider package version EF Core version Differences for identical seed data
    Npgsql 6.0.7 6.0.7 None
    Npgsql 6.0.29 6.0.36 None
    Npgsql 7.0.0 7.0.0 One redundant update
    Npgsql 8.0.11 8.0.31 One redundant update
    Npgsql 9.0.4 9.0.4 One redundant update
    Npgsql 9.0.4 9.0.21 One redundant update
    Npgsql 10.0.3 10.0.13 One redundant update
    Npgsql 11.0.0-rc.1.1 11.0.0-rc.1.26425.128 One redundant update
    SQL Server 9.0.4 9.0.4 None

    The stable-package comparisons were run on .NET 10; the 11 prerelease comparison was run on .NET 11 RC2. The original .NET 9 runtime was not used.

    Comparer mismatch

    For two distinct List<string> instances containing "A", "B", "C", the Npgsql 9.0.4 property comparers give:

    Comparer Equal
    GetValueComparer() true
    GetKeyValueComparer() false
    GetProviderValueComparer() false

    EF 6 compares model seed values using the value comparer, whereas EF 7's seed-data differ uses the column's provider value comparer. The Npgsql array mapping supplies an element-wise value comparer but does not explicitly supply a key/provider comparer. This explains why equal list contents can nevertheless be treated as changed by migrations.

    Explicitly setting a sequence-based ValueComparer<List<string>>, as in the workaround above, removed the difference. Scaffolding another migration against the existing snapshot with that comparer configured also produced an empty migration.

    Related issues

    • dotnet/efcore#36942 is the same report, already closed after it did not reproduce on SQL Server and was redirected here. The independent SQL Server comparison above agrees with that result; this issue should remain in the Npgsql repository.
    • dotnet/efcore#27374 has a similar repeated-seed-update symptom for spatial values, but is not an established duplicate of this primitive-list mapping bug.
    minimal repro

    Repro.csproj:

    <Project Sdk="Microsoft.NET.Sdk">
      <PropertyGroup>
        <OutputType>Exe</OutputType>
        <TargetFramework>net10.0</TargetFramework>
        <ImplicitUsings>enable</ImplicitUsings>
        <Nullable>enable</Nullable>
      </PropertyGroup>
      <ItemGroup>
        <PackageReference Include="Npgsql.EntityFrameworkCore.PostgreSQL" Version="9.0.4" />
        <PackageReference Include="Microsoft.EntityFrameworkCore.Design" Version="9.0.4">
          <PrivateAssets>all</PrivateAssets>
        </PackageReference>
      </ItemGroup>
    </Project>

    Program.cs:

    using Microsoft.EntityFrameworkCore;
    using Microsoft.EntityFrameworkCore.Infrastructure;
    using Microsoft.EntityFrameworkCore.Metadata;
    using Microsoft.EntityFrameworkCore.Migrations;
    using Microsoft.Extensions.Logging;
    
    using var source = new BlogContext();
    using var target = new BlogContext();
    var sourceModel = source.GetService<IDesignTimeModel>().Model;
    var targetModel = target.GetService<IDesignTimeModel>().Model;
    var operations = target.GetService<IMigrationsModelDiffer>().GetDifferences(
        sourceModel.GetRelationalModel(), targetModel.GetRelationalModel());
    foreach (var command in target.GetService<IMigrationsSqlGenerator>().Generate(operations, targetModel))
    {
        Console.WriteLine(command.CommandText);
    }
    
    public class BlogContext : DbContext
    {
        public DbSet<MyEntity> MyEntities { get; set; }
    
        protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
            => optionsBuilder
                .UseNpgsql("Host=localhost;Database=issue3635")
                .EnableServiceProviderCaching(false)
                .LogTo(Console.WriteLine, LogLevel.Information)
                .EnableSensitiveDataLogging();
    
        protected override void OnModelCreating(ModelBuilder modelBuilder)
            => modelBuilder.Entity<MyEntity>().HasData(
                new MyEntity { Id = 1, Tags = new List<string> { "A", "B", "C" } });
    }
    
    public class MyEntity
    {
        public int Id { get; set; }
        public List<string> Tags { get; set; } = null!;
    }

    EnableServiceProviderCaching(false) ensures that the two contexts build independent models, rather than comparing the same cached model and seed objects.

    Run dotnet run. Expected: no migration SQL. Actual:

    UPDATE "MyEntities" SET "Tags" = ARRAY['A','B','C']::text[]
    WHERE "Id" = 1;

    For the original scaffolding scenario, using dotnet-ef 9.0.4 in a fresh copy of the project:

    dotnet ef migrations add Initial
    dotnet ef migrations add Unchanged
    dotnet ef migrations add StillUnchanged

    Both Unchanged and StillUnchanged contain:

    migrationBuilder.UpdateData(
        table: "MyEntities",
        keyColumn: "Id",
        keyValue: 1,
        column: "Tags",
        value: new List<string> { "A", "B", "C" });
  5. added a commit that references this issue on Oct 18, 2026
    efa0486
  6. self-assigned this
    on Oct 18, 2026
  7. added this to the 10.0.4 milestone on Oct 18, 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