npgsql / efcore.pg

Entity Framework Core provider for PostgreSQL
PostgreSQL License
1.54k stars 226 forks source link

Serialization options for System.Text.Json support #1107

Open brendan-nobadthing opened 4 years ago

brendan-nobadthing commented 4 years ago

Hi,

I'm looking to serialize a model containing Nodatime types into a jsonb data field. Right now this serializes a whole bunch of individual fields from the nodatime type. I see a couple of days ago, jon skeet published a beta for system.text.json serlialisation support for nodatime: https://www.nuget.org/packages/NodaTime.Serialization.SystemTextJson

This looks like just the thing I'm looking for but I'm not sure how to wire this config into the serialization used by npgsql & EF core.

Any ideas / suggestions? Thanks!

chrisbbe commented 10 months ago

I tried that as well, but the same error: 42804: column "data" is of type jsonb but expression is of type text

            person.Property(e => e.Data)
                .HasColumnName("data")
                .HasConversion(MyValueConverter.Instance);
public sealed class MyValueConverter : ValueConverter<Dictionary<string, object?>, string>
{
    public static readonly MyValueConverter Instance = new();

    public MyValueConverter() : base(
        status =>
            JsonSerializer.Serialize(status, (JsonSerializerOptions?)null),
        value =>
            JsonSerializer.Deserialize<Dictionary<string, object?>>(value, (JsonSerializerOptions?)null) ??
            new Dictionary<string, object?>(StringComparer.OrdinalIgnoreCase))
    {
    }
}
roji commented 10 months ago

Have you specified the column type as being jsonb in the EF configuration?

In any case, this is quite off-topic for this issue, if you're still having difficulties, please open a new issue with a minimal, runnable code sample.