Skip to content

JSON column polymorphic collection only serializing base property #6217 #3620

Closed as duplicate

Description

@Issung

Hi all, I've been tearing my brain apart for 3 days trying to figure this one out. Hoping I'm just missing something stupid.

Long story short I want to save rows in my database that have a JSONB column, that is a collection of polymorphic objects, so I can save a list of changes made on a revision of an item.

Like so:

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

    public List<ItemChange> Changes { get; set; } = [];
}

[JsonPolymorphic(TypeDiscriminatorPropertyName = "$type")]
[JsonDerivedType(typeof(NameChange), nameof(NameChange))]
[JsonDerivedType(typeof(DescriptionChange), nameof(DescriptionChange))]
public class ItemChange
{
    public string BaseProp { get; set; } = "Hello";
}

public class NameChange : ItemChange { public required string NewName { get; set; } }

public class DescriptionChange : ItemChange { public required string NewDescription { get; set; } }

Following the advice on npgsql.org I configured my DbContext like so:

public class Context : DbContext
{
    public DbSet<ItemRevision> Revisions => Set<ItemRevision>();

    protected override void OnConfiguring(DbContextOptionsBuilder options)
    {
        options.UseNpgsql(
            "Host=localhost;Port=15651;Username=postgres;Password=password;Database=testdb",
            o =>
            {
                o.ConfigureDataSource(s =>
                {
                    s.EnableDynamicJson();
                    s.ConfigureJsonOptions(new JsonSerializerOptions
                    {
                        AllowOutOfOrderMetadataProperties = true,
                    });
                });
            }
        );

        options
            .LogTo((str) => Debug.WriteLine(str), [DbLoggerCategory.Database.Command.Name], Microsoft.Extensions.Logging.LogLevel.Trace)
            .EnableSensitiveDataLogging();
    }

    protected override void OnModelCreating(ModelBuilder builder)
    {
        base.OnModelCreating(builder);

        builder.Entity<ItemRevision>(te =>
        {
            te.OwnsMany(e => e.Changes, nav =>
            {
                nav.ToJson();
            });
        });
    }
}

Everything seems OK, but this test fails with this message Assert.IsInstanceOfType failed. 'value' expression: 'loaded.Changes[0]'. Expected type:<NpgsqlPolymorphicJsonBugRepro.NameChange>. Actual type:<NpgsqlPolymorphicJsonBugRepro.ItemChange>.

[TestClass]
public sealed class Tests
{
    [TestMethod]
    public void Test()
    {
        int? revisionId;

        using (var context = new Context())
        {
            context.Database.EnsureDeleted();
            context.Database.EnsureCreated();

            var entity = new ItemRevision
            {
                Changes = [ new NameChange { NewName = "Name" } ],
            };

            var changesJson = JsonSerializer.Serialize(entity.Changes);
            Assert.AreEqual(    // This passes.
                actual: changesJson,
                expected: @"[{""$type"":""NameChange"",""NewName"":""Name"",""BaseProp"":""Hello""}]"
            );

            context.Revisions.Add(entity);
            context.SaveChanges();  // This saves with `@p0='[{"BaseProp":"Hello"}]'`.

            revisionId = entity.Id;
        }

        using (var context = new Context())
        {
            var loaded = context.Revisions.First();
            Assert.IsInstanceOfType<NameChange>(loaded.Changes[0]); // This fails.
        }
    }
}

This is because upon the save, the data put into the database contains only the base field and none of the polymorphic stuff (extra fields or $type descriminator, see @p0).

Executed DbCommand (34ms) [Parameters=[@p0='[{"BaseProp":"Hello"}]' (Nullable = false) (DbType = Object)], CommandType='Text', CommandTimeout='30']
INSERT INTO "Revisions" ("Changes")
VALUES (@p0)
RETURNING "Id";

I believe I have the polymorphic attributes setup because the JSON test within the test passes as expected.

The full runnable minimal example can be found here: https://github.com/Issung/npgsql-polymorphic-json-bug-repro

Please help me, I'm losing my mind! 😭

Activity

  1. roji commented on Sep 19, 2025

    @roji
    Member

    tl;dr ToJson() does not support inheritance/polymorphism, that's dotnet/efcore#27779. If you need inheritance, you can use (legacy) POCO mapping (docs).

    When using EF Core's ToJson(), EF does not internally just hand the to System.Text.Json for serialization - it handles serialization itself; this is because EF doesn't just serialize and deserialize your objects, it also has to be able to generate SQL to query on properties inside them, and so must fully model the types involved and handle the serialization. For example, for your hierarchy above, EF would need to handle queries that use the LINQ OfType operator to filter only DescriptionChange instances - that's not implemented.

    If you absolutely need inheritance, you can use the older POCO mapping, where the PG EF provider simply hands off the objects to S.T.Json for serialization. That supports everything that S.T.Json supports, but the querying capabilities are severely limited compared to what ToJson() supports.

  2. stigrune commented on Nov 20, 2025

    @stigrune

    Thank you for the clarification. I had assumed this would work as well, so I was glad that I found this issue before wasting much time on it.

    Can we assume that the older POCO mapping feature will remain available until EF Core offers native support for polymorphism?

  3. roji commented on Nov 20, 2025

    @roji
    Member

    @stigrune that's right, there's no plan to remove the old POCO mapping at this point.

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

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions