JsonToJsonNodePropertyHandler

A property handler that maps the SQL Server json type into a JsonNode property.

A property handler that maps the SQL Server json type, which the database returns as a string, into a JsonNode property.

This handler is compiled only for .NET 8 and later. It is not available on the netstandard2.0 target of the RepoDb package.

Overview

Name Description
Class JsonToJsonNodePropertyHandler
Namespace RepoDb.PropertyHandlers
Package RepoDb
Implements IPropertyHandler<string, JsonNode>
Column type The SQL Server json type, returned by the database as a string
Property type JsonNode
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 JsonNode. A null or an empty value is returned as null.
Set Property to database Converts the JsonNode into its compact JSON text via ToJsonString(). 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(JsonToJsonNodePropertyHandler))]
    public JsonNode 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 = JsonNode.Parse("{\"color\":\"red\"}") });

    var product = connection.Query<Product>(e => e.Id == 1).First();
    product.Attributes["color"] = "blue"; // JsonNode is mutable
}

Fluent Mapping

To configure via FluentMapper:

FluentMapper
    .Entity<Product>()
    .PropertyHandler<JsonToJsonNodePropertyHandler>(e => e.Attributes);

Property Level Mapping

To configure via PropertyHandlerMapper:

PropertyHandlerMapper.Add<Product, JsonToJsonNodePropertyHandler>(e => e.Attributes, new JsonToJsonNodePropertyHandler(), true);

Type Level Mapping

To apply the handler to every property of the type JsonNode:

PropertyHandlerMapper.Add<JsonNode, JsonToJsonNodePropertyHandler>(new JsonToJsonNodePropertyHandler(), true);

See Also