JsonToJsonDocumentPropertyHandler
A property handler that maps a database json column, such as the MySQL JSON type, into a JsonDocument property.
A property handler that maps a database json column (for example, the MySQL JSON type) into a JsonDocument property.
JsonDocumentisIDisposable. The document created by this handler is owned by the entity, and it is the responsibility of the caller to dispose it. To avoid the disposal, use JsonToJsonElementPropertyHandler or JsonToJsonNodePropertyHandler.
This handler is compiled only for .NET 8 and later. It is not available on the
netstandard2.0target of the RepoDb package.
Overview
| Name | Description |
|---|---|
| Class | JsonToJsonDocumentPropertyHandler |
| Namespace | RepoDb.PropertyHandlers |
| Package | RepoDb |
| Implements | IPropertyHandler<string, JsonDocument> |
| Column type | A json column (for example, the MySQL JSON type), returned by the driver as a string |
| Property type | JsonDocument |
| Availability | Not available on the netstandard2.0 target of the package; requires .NET 8 or later. |
Conversions
| Method | Direction | Description |
|---|---|---|
| Get | Database to property | Parses the JSON text into a JsonDocument. A null or an empty value is returned as null. |
| Set | Property to database | Converts the JsonDocument into its raw JSON text via RootElement.GetRawText(). A null value is written as null. |
Usability
Bind the handler to the property that maps to a JSON column.
Attribute
public class Product
{
public int Id { get; set; }
[Map("attributes"), PropertyHandler(typeof(JsonToJsonDocumentPropertyHandler))]
public JsonDocument Attributes { get; set; }
}
Once bound, the library invokes the handler automatically when the property is read or written.
using (var connection = new MySqlConnection(connectionString))
{
var attributes = JsonDocument.Parse("{\"color\":\"red\"}");
connection.Insert(new Product { Id = 1, Attributes = attributes });
var product = connection.Query<Product>(e => e.Id == 1).First();
var color = product.Attributes.RootElement.GetProperty("color").GetString();
product.Attributes.Dispose(); // the caller owns the document
}
Fluent Mapping
To configure via FluentMapper:
FluentMapper
.Entity<Product>()
.PropertyHandler<JsonToJsonDocumentPropertyHandler>(e => e.Attributes);
Property Level Mapping
To configure via PropertyHandlerMapper:
PropertyHandlerMapper.Add<Product, JsonToJsonDocumentPropertyHandler>(e => e.Attributes, new JsonToJsonDocumentPropertyHandler(), true);
Type Level Mapping
To apply the handler to every property of the type JsonDocument:
PropertyHandlerMapper.Add<JsonDocument, JsonToJsonDocumentPropertyHandler>(new JsonToJsonDocumentPropertyHandler(), true);