JsonToEntityPropertyHandler

A property handler that maps the SQL Server json type, returned as a string, into an entity property via System.Text.Json.

A property handler that maps the SQL Server json type, which the database returns as a string, into a TEntity property. The conversion is performed by JsonSerializer.

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 JsonToEntityPropertyHandler<TEntity>
Namespace RepoDb.PropertyHandlers
Package RepoDb
Implements IPropertyHandler<string, TEntity>
Column type The SQL Server json type, returned by the database as a string
Property type TEntity
Availability Not available on the netstandard2.0 target of the package; requires .NET 8 or later.

Conversions

Method Direction Description
Get Database to property Deserializes the JSON text into a TEntity via JsonSerializer.Deserialize<TEntity>(). A null or an empty value is returned as default.
Set Property to database Serializes the TEntity into its JSON text via JsonSerializer.Serialize(). A null value is written as null.

Usability

Bind the handler, closed over the entity type, to the property that maps to a json column.

Attribute

public class Customer
{
    public int Id { get; set; }

    [Map("address"), PropertyHandler(typeof(JsonToEntityPropertyHandler<Address>))]
    public Address Address { 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 Customer { Id = 1, Address = new Address { Street = "1 Main St", City = "Oslo" } });
    var customer = connection.Query<Customer>(e => e.Id == 1).First();
    // customer.Address is an Address deserialized from the json column
}

Fluent Mapping

To configure via FluentMapper:

FluentMapper
    .Entity<Customer>()
    .PropertyHandler<JsonToEntityPropertyHandler<Address>>(e => e.Address);

Property Level Mapping

To configure via PropertyHandlerMapper:

PropertyHandlerMapper.Add<Customer, JsonToEntityPropertyHandler<Address>>(e => e.Address, new JsonToEntityPropertyHandler<Address>(), true);

Type Level Mapping

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

PropertyHandlerMapper.Add<Address, JsonToEntityPropertyHandler<Address>>(new JsonToEntityPropertyHandler<Address>(), true);

A type level mapping is process-wide: it is applied to every Address property of every entity and connection, not only to the intended column. Prefer the attribute, fluent or property level mapping unless every Address property maps to a json column.

See Also