coder123
coder123

Reputation: 1

Unable to Persist HashSet<T> with jsonb Column Type in EF Core after Upgrading to .NET 9 and PostgreSQL 9.0.1

I'm upgrading a project from .NET 6 to .NET 9 and PostgreSQL to version 9.0.1. In my domain model, I have the following property:

public HashSet<Guid> Property { get; set; }

In the database, both properties are stored as jsonb columns with the default value set to '[]'::jsonb. However, after upgrading, I'm encountering the following error:

System.InvalidCastException: Unable to cast object of type 'System.Collections.Generic.HashSet`1[System.Guid]' to type 'System.Collections.Generic.IList`1[System.Guid]'.

I suspect the issue is related to how EF Core serializes HashSet<T> and jsonb columns in the upgraded environment.

Additional Details: Previous EF Core/Database Behavior: This worked seamlessly in .NET 6 and PostgreSQL (older version).

My Questions: Is there a breaking change in EF Core or PostgreSQL that affects how HashSet<T> is serialized/deserialized for jsonb columns? How can I correctly persist and query HashSet<T> with jsonb in the upgraded environment? Is there a workaround or a best practice to avoid this InvalidCastException?

I tried to somehow manage the serialization manually:

builder
    .Property(x => x.Property)
    .HasColumnType("jsonb")
    .HasDefaultValueSql("'[]'::jsonb")
    .HasConversion(
        v => JsonSerializer.Serialize(v, new JsonSerializerOptions { DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull }),
        v => JsonSerializer.Deserialize<HashSet<Guid>>(v, new JsonSerializerOptions { PropertyNameCaseInsensitive = true }) ?? new HashSet<Guid>()
);

But it didn't helped.

Upvotes: 0

Views: 44

Answers (0)

Related Questions