dotnet / efcore

EF Core is a modern object-database mapper for .NET. It supports LINQ queries, change tracking, updates, and schema migrations.
https://docs.microsoft.com/ef/
MIT License
13.79k stars 3.19k forks source link

Support data seeding for JSON columns #32017

Open AndriySvyryd opened 1 year ago

navferty commented 2 months ago

When I try to use entity with a property that is mapped to jsonb column, it keeps creating update scripts in each subsequent migration.

Sample DB contex:

public sealed class BloggingContext : DbContext
{
    public DbSet<Post> Posts { get; set; }

    protected override void OnConfiguring(DbContextOptionsBuilder options)
        => options.UseNpgsql("<connectionstring>");

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder.Entity<Post>()
            .Property(e => e.Contents)
            .HasColumnType("jsonb");

        modelBuilder.Entity<Post>()
            .HasData(new Post
            {
                Id = 1,
                Contents = new Dictionary<string, string> { { "key", "value" } }
            });
    }
}

public class Post
{
    public int Id { get; init; }
    public required Dictionary<string, string> Contents { get; set; }
}

After I created initial migration (which include InsertData call as expected), if I try to add next migration, it shows warning message ("An operation was scaffolded that may result in the loss of data") and migration contains update script:

protected override void Up(MigrationBuilder migrationBuilder)
{
    migrationBuilder.UpdateData(
        table: "Posts",
        keyColumn: "Id",
        keyValue: 1,
        column: "Contents",
        value: new Dictionary<string, string> { ["key"] = "value" });
}

Using Microsoft.EntityFrameworkCore.Design version 8.0.8 and Npgsql.EntityFrameworkCore.PostgreSQL version 8.0.4

roji commented 2 months ago

@navferty the jsonb support via Dictionary<string, string> is PG-specific, and isn't covered by this issue. You can open an issue for this in https://github.com/npgsql/efcore.pg.