JsonToJsonElementPropertyHandler
A property handler that maps the SQL Server json type into a JsonElement property.
A property handler that maps the SQL Server json type, which the database returns as a string, into a JsonElement property.
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 | JsonToJsonElementPropertyHandler |
| Namespace | RepoDb.PropertyHandlers |
| Package | RepoDb |
| Implements | IPropertyHandler<string, JsonElement> |
| Column type | The SQL Server json type, returned by the database as a string |
| Property type | JsonElement |
| 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 and returns a clone of the root element, which is independent of the parsed document and does not need to be disposed. A null or an empty value is returned as default(JsonElement), whose ValueKind is Undefined. |
| Set | Property to database | Converts the JsonElement into its raw JSON text via GetRawText(). An Undefined element 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(JsonToJsonElementPropertyHandler))]
public JsonElement Attributes { get; set; }
}
Once bound, the library invokes the handler automatically when the property is read or written.
using (var connection = new SqlConnection(connectionString))
{
connection.Insert(new Product { Id = 1, Attributes = JsonDocument.Parse("{\"color\":\"red\"}").RootElement.Clone() });
var product = connection.Query<Product>(e => e.Id == 1).First();
var color = product.Attributes.GetProperty("color").GetString();
}
Fluent Mapping
To configure via FluentMapper:
FluentMapper
.Entity<Product>()
.PropertyHandler<JsonToJsonElementPropertyHandler>(e => e.Attributes);
Property Level Mapping
To configure via PropertyHandlerMapper:
PropertyHandlerMapper.Add<Product, JsonToJsonElementPropertyHandler>(e => e.Attributes, new JsonToJsonElementPropertyHandler(), true);
Type Level Mapping
To apply the handler to every property of the type JsonElement:
PropertyHandlerMapper.Add<JsonElement, JsonToJsonElementPropertyHandler>(new JsonToJsonElementPropertyHandler(), true);