-
Notifications
You must be signed in to change notification settings - Fork 133
Open
Labels
questionFurther information is requestedFurther information is requested
Description
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!
Reactions are currently unavailable
Metadata
Metadata
Assignees
Labels
questionFurther information is requestedFurther information is requested