Skip to content

Json converter is ignored when reading from jsonb column #3489

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
elementum opened this issue Mar 5, 2025 · 0 comments
Open

Json converter is ignored when reading from jsonb column #3489

elementum opened this issue Mar 5, 2025 · 0 comments

Comments

@elementum
Copy link

elementum commented Mar 5, 2025

I'm having a problem similar to #2325

I have a jsonb column that stores an object with enum property. I configured all enums to serialize as strings. However even though It is written as string it is still read as number that results in error.

Here is a console app that reproduces the problem:

using System.Text.Json.Serialization;
using Microsoft.EntityFrameworkCore;
using Npgsql;

using var db = new MyContext();
db.Database.EnsureCreated();

var user = new User()
{
    Details = new()
    {
        Address = "some address",
        UserType = UserType.Admin
    }
};

db.Users.Add(user);
db.SaveChanges(); // saved successfully {"Address": "some address", "UserType": "Admin"}

user = db.Users.FirstOrDefault(); // read whole user successfully

var userType = db.Users.Select(x => x.Details.UserType).FirstOrDefault(); // fails  22P02: invalid input syntax for type integer: "Admin"
Console.WriteLine(userType);

class MyContext : DbContext
{
    public DbSet<User> Users { get; set; } = null!;

    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
    {
        var dataSource = new NpgsqlDataSourceBuilder("Host=localhost;Port=5432;Database=any;Username=any;Password=any")
            .EnableDynamicJson()
            .ConfigureJsonOptions(new()
            {
                PropertyNameCaseInsensitive = true,
                Converters =
                {
                    new JsonStringEnumConverter(allowIntegerValues: true),
                },
            })
            .Build();
        
        optionsBuilder.UseNpgsql(dataSource);
    }

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder.Entity<User>(o =>
        {
            o.Property(p => p.Details).HasColumnType("jsonb");
        });
    }
}

record User
{
    public long Id { get; set; }
    public UserDetails Details { get; set; }
}
record UserDetails
{
    public string Address { get; set; }
    public UserType UserType { get; set; }
}

enum UserType
{
    Manager = 1,
    Admin = 2
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant