Skip to content
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

Question: How to use JSONB columns (with PostgreSQL) #1181

Open
jan opened this issue Sep 6, 2024 · 1 comment
Open

Question: How to use JSONB columns (with PostgreSQL) #1181

jan opened this issue Sep 6, 2024 · 1 comment
Labels
question Further information is requested

Comments

@jan
Copy link

jan commented Sep 6, 2024

In a PostgreSQL database with a JSONB column, how should we define this field in an entity class?

This works:

    [NpgsqlDbType(NpgsqlDbType.Jsonb)]
    public string Metadata { get; init; }

Is there any way to automatically get the structured data?

Or do we have to seriaize and deserialize this ourselves?

    public Dictionary<string, object?> MetadataDictionary {
        get {
            return JsonSerializer.Deserialize<Dictionary<string, object?>>(Metadata) ?? new Dictionary<string, object?>();
        }
        init {
            Metadata = Newtonsoft.Json.JsonConvert.SerializeObject(value);
        }
    }

For example, in Dapper you can define & register a type handler:

public class DapperDictionaryTypeHandler : SqlMapper.TypeHandler<Dictionary<string, object>> {
    public override void SetValue(IDbDataParameter parameter, Dictionary<string, object>? value) {
        parameter.Value = value == null ? null : Newtonsoft.Json.JsonConvert.SerializeObject(value);
    }

    public override Dictionary<string, object>? Parse(object? value) {
        return value == null ? null : JsonSerializer.Deserialize<Dictionary<string, object>>((string) value);
    }
}

And then you can define the entity field directly, without annotations, as

    public Dictionary<string, object?> Metadata { get; init; }

Would be great if you could add an example best practice to the docs.

Thank you!

@jan jan added the question Further information is requested label Sep 6, 2024
@jan
Copy link
Author

jan commented Sep 6, 2024

Also, it would be great to be able to achieve the equivalent of [NpgsqlDbType(NpgsqlDbType.Jsonb)] without an annotation, similar to how RepoDbAutoMapper works.

Context: in one of our projects we try to use a Clean Architecture project structure and we can't (well, it feels wrong to) use NpgsqlDbType inside of the Domain project.

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

No branches or pull requests

1 participant