Skip to content

Enhancement: Support First-Class JSON/JSONB Mapping and Querying #1312

Open

Description

@mikependon

Support First-Class JSON/JSONB Mapping and Querying

Description

Introduce first-class JSON/JSONB support in RepoDB for SQL Server, PostgreSQL, and Oracle, allowing strongly typed .NET objects to be stored, retrieved, and queried against JSON-backed database columns.

The implementation should introduce a DbJsonValue<T> abstraction that handles serialization/deserialization while allowing RepoDB's expression parser to translate property and array access into the database-specific JSON syntax.

Example Model

[Table(nameof(JsonTestClass))]
public record class JsonTestClassValues
{
    public int Id { get; set; }

    public string Name { get; set; } = string.Empty;

    public DbJsonValue<JsonBTestClass> JsonNode { get; set; }

    public DbJsonValue<JsonBTestClass>? Object { get; set; }

    public DbJsonValue<string[]> Array { get; set; }
}

Insert

await connection.InsertAsync(new JsonTestClassValues
{
    Id = 1,
    Name = "Test",
    JsonNode = new JsonBTestClass { Id = 5 },
    Object = new JsonBTestClass(),
    Array = new[] { "a", "b" }
});

Query via ExtractValue

var result = await connection.QueryAsync<JsonTestClassValues>(
    x => x.JsonNode.ExtractValue(v => v.Id) == 5);

Query via Strongly Typed Value

RepoDB should also recognize access through Value and automatically translate it into the appropriate JSON expression.

var result = await connection.QueryAsync<JsonTestClassValues>(
    x => x.JsonNode.Value.Id == 5);

Nested objects and array access should follow the same expression-based approach.

Goals

  • Introduce DbJsonValue<T> as a strongly typed JSON value abstraction.
  • Automatically serialize T when inserting or updating.
  • Automatically deserialize JSON values when querying.
  • Support JSON property access through RepoDB expressions.
  • Support nested objects and arrays.
  • Translate expressions into provider-specific JSON syntax.
  • Support SQL Server, PostgreSQL, and Oracle.
  • Keep JSON handling provider-independent from the consumer's perspective.

Acceptance Criteria

  • DbJsonValue<T> works with Insert, Update, Query, and other applicable RepoDB operations.
  • JSON values round-trip correctly between .NET and the database.
  • ExtractValue(...) expressions are translated into native JSON queries.
  • Value.Property expressions are automatically recognized and translated.
  • Nested properties and array access are supported.
  • SQL Server, PostgreSQL, and Oracle have integration tests covering JSON read, write, update, and filtering.
  • Existing non-JSON RepoDB behavior remains unaffected.

Reference: AmpScm#25

Activity

  1. self-assigned this
    on Aug 31, 2026
  2. added
    enhancement
    request
    on Aug 31, 2026
  3. mikependon commented on Aug 31, 2026

    @mikependon
    OwnerAuthor

    Hi @AntyaDev @rhuijben, I tried to analyze this further and this is a kind of edge-case but it is already supported. Are you aware that you can already do this via Property Handler? Property handler is there to support whatever interceptors you would like to do with your properties against the database types.

    Basically, on the above use-case, you can do the following in the bottom.

    using System.Text.Json;
    
    namespace RepoDb.PropertyHandlers;
    
    public sealed class DbJsonValuePropertyHandler<T> : IPropertyHandler<string?, DbJsonValue<T>>
    {
        private static readonly JsonSerializerOptions JsonOptions = new()
        {
            PropertyNameCaseInsensitive = true
        };
    
        public DbJsonValue<T> Get(string? input, PropertyHandlerGetOptions options)
            => new DbJsonValue<T>(JsonSerializer.Deserialize<T>(input, JsonOptions));
    
        public string? Set(DbJsonValue<T> input, PropertyHandlerSetOptions options)
            => JsonSerializer.Serialize(input.Value, JsonOptions);
    }

    Then map it fluently like below.

    PropertyHandlerMapper
        .Add<DbJsonValue<JsonBTestClass>,
             DbJsonValuePropertyHandler<JsonBTestClass>>(true);

    Let me know your thoughts.

  4. mikependon commented on Aug 31, 2026

    @mikependon
    OwnerAuthor

    More into it. It is on my plan to add the pre-defined PropertyHandlers and Resolvers as I gain insights when expanding the library to many DB providers. They have different requirements on .NET to DB Types conversion, that is why some are needed. I also have challenges supporting the XML in Oracle and MariaDB due to these and some of them I have to put to limitations for now.

  5. rhuijben commented on Aug 31, 2026

    @rhuijben
    Collaborator

    Some things can be handled on this layer, but some db implementations need other overrides. The current property mapping doesn't work intuitively with nullable fields in the database.
    (Some cases are more like hidden bugs.. some break nullability annotations, etc.)

    I think the nullability of value types should be handled outside these handlers (by RepoDB), which would make things much easier to implement... But may be quite a breaking change.

    And especially things like Json (and perhaps vectors) could also use linq query support, and then there needs to be more integration in type mappings on multiple layers, depending on db specifics.

  6. mikependon commented on Aug 31, 2026

    @mikependon
    OwnerAuthor

    OK, I will evaluate further and then probably we can support this if it is already a use-case you are using there. Do you happen to share to which DB provider did you applied this for? Is it only SQL Server?

  7. mikependon commented on Aug 31, 2026

    @mikependon
    OwnerAuthor

    In relation to our limitation page, each of the items here are to be user story of the future. I keep adding them here while expanding the library so we all can work together in the future. I hope that this is one of such.

  8. mikependon commented on Aug 31, 2026

    @mikependon
    OwnerAuthor

    List of DB providers that support XMLs.

    XML Support Across RepoDB Database Providers

    The table below summarizes the level of native XML support available across the database providers supported by RepoDB.

    Database Provider Native XML Type First-Class XML XML Type / Capability
    SQL Server ✅ ✅ Strong xml, XQuery, nodes(), value(), query(), exist(), XML indexes
    PostgreSQL ✅ ✅ Strong xml, XMLPARSE, XMLSERIALIZE, XPath, XMLTABLE
    EnterpriseDB (EPAS) ✅ ✅ Strong PostgreSQL xml, SQL/XML functions, PostgreSQL-compatible XML functionality
    Oracle ✅ ✅ Strong XMLType, XMLQuery, XMLTable, XMLExists
    IBM Db2 ✅ ✅ Strong XML, SQL/XML, XPath/XQuery, XML indexes
    CockroachDB ❌ ❌ No native xml type; XML can be stored as STRING or BYTES
    SAP HANA ❌ / Limited ❌ Primarily string/LOB-based XML storage and processing
    MySQL ❌ ❌ No native XML data type
    MariaDB ❌ ❌ No native XML data type
    Firebird ❌ ❌ XML can be stored using text/BLOB columns
    SQLite ❌ ❌ XML can be stored as TEXT or BLOB
    ClickHouse ❌ ❌ No general-purpose native XML column type
    Vertica ❌ ❌ XML processing/loading capabilities, but no comparable native XML column type

    Recommended RepoDB First-Class XML Support

    The following providers are candidates for native DbXmlValue<T> support:

    • SQL Server
    • PostgreSQL
    • EnterpriseDB (EPAS)
    • Oracle
    • IBM Db2

    These databases provide native XML data types and database-side XML querying capabilities.

    public class Entity
    {
        public int Id { get; set; }
    
        public DbXmlValue<MyModel> Document { get; set; }
    }

    For databases without native XML support, RepoDB could optionally support DbXmlValue<T> through serialization into the appropriate textual or LOB database type.

  9. mikependon commented on Aug 31, 2026

    @mikependon
    OwnerAuthor

    List of DB providers that support JSON.

    JSON Support Across RepoDB Database Providers

    The table below summarizes JSON support across the database providers supported by RepoDB.

    Database Provider Native JSON Type First-Class JSON JSON Type / Capability
    PostgreSQL ✅ ✅ Strong json, jsonb, JSON operators (->, ->>), JSONPath, indexing
    EnterpriseDB (EPAS) ✅ ✅ Strong PostgreSQL-compatible json / jsonb, operators, JSONPath and indexing
    CockroachDB ✅ ✅ Strong JSONB, JSON operators, containment and inverted indexes
    Oracle ✅* ✅ Strong Native JSON type on modern versions; JSON_VALUE, JSON_QUERY, JSON_TABLE, JSON search/indexing
    MySQL ✅ ✅ Strong Native JSON, JSON_EXTRACT, ->, ->>, JSON_TABLE, JSON functions
    SQL Server ⚠️ Version-dependent ✅ Strong Native json type on newer SQL Server versions; historically JSON stored in nvarchar, with JSON_VALUE, JSON_QUERY, OPENJSON, JSON_MODIFY
    MariaDB ⚠️ Alias ✅ JSON is generally an alias for LONGTEXT, with JSON validation/functions
    Db2 ⚠️ ✅ Extensive SQL/JSON functionality; storage capabilities depend on Db2 platform/version
    SAP HANA ⚠️ Version-dependent ✅ JSON document/storage and SQL JSON functionality vary by HANA version
    ClickHouse ✅* ✅ JSON type in modern ClickHouse plus extensive JSON extraction/processing functions
    SQLite ❌ ✅* JSON stored as TEXT/BLOB; JSON1/modern built-in JSON functions and JSONB representation
    Firebird ❌ ⚠️ Limited No comparable native JSON column type; typically stored as text/BLOB
    Vertica ⚠️ ✅ Semi-structured data support and JSON parsing/querying capabilities

    Note: "First-Class JSON" refers to meaningful database-side JSON querying/manipulation capabilities and does not necessarily mean that the database has a physically distinct native JSON storage type.

    Recommended RepoDB JSON Support

    Unlike XML, DbJsonValue<T> can reasonably become a common RepoDB abstraction across most providers.

    public class Entity
    {
        public int Id { get; set; }
    
        public DbJsonValue<MyModel> Document { get; set; }
    }

    For example:

    await connection.InsertAsync(new Entity
    {
        Id = 1,
        Document = new MyModel
        {
            Id = 100,
            Name = "RepoDB"
        }
    });

    Strongly Typed Queries

    RepoDB could recognize strongly typed access to JSON properties:

    var result = await connection.QueryAsync<Entity>(
        e => e.Document.Value.Id == 100);

    or explicitly:

    var result = await connection.QueryAsync<Entity>(
        e => e.Document.ExtractValue(x => x.Id) == 100);

    The RepoDB connector would translate the expression into the appropriate database-specific JSON expression.

    Conceptually:

    DbJsonValue<T>
           │
           ├── Serialization / Deserialization
           │
           └── Expression Translation
                        │
                        ├── SQL Server
                        ├── PostgreSQL
                        ├── EnterpriseDB
                        ├── CockroachDB
                        ├── Oracle
                        ├── MySQL
                        ├── MariaDB
                        ├── Db2
                        ├── ClickHouse
                        ├── SAP HANA
                        ├── SQLite
                        ├── Firebird
                        └── Vertica
    

    This keeps DbJsonValue<T> database-independent while allowing each RepoDB connector to use the best JSON capabilities available from its underlying database.

  10. rhuijben commented on Sep 3, 2026

    @rhuijben
    Collaborator

    I have the basic support for this working in the AmpScm fork, but I hope we can enhance this later on when db providers improve their support. Postgresql is already some steps ahead and I think SqlServer is working on more too.

    Thanks for modelling this here like my initial work... But if somebody has better ideas, please join in, as we might be able to do better. The nice thing about this model is that it allows both native json queries and accessing the object model... like we do with other queries in RepoDB

  11. mikependon commented on Sep 3, 2026

    @mikependon
    OwnerAuthor

    @rhuijben the model above is from @AntyaDev post in your fork which eventually mimic your implementation. I tried to model it here to see how much extent this capability will be applied to given with the number of providers we are supporting. Can you make a PR of your initial implementation to here?

  12. AntyaDev commented on Sep 6, 2026

    @AntyaDev

    Thanks @mikependon @rhuijben for your input!

    I really like the examples with JSON support :)

  13. mikependon commented on Sep 13, 2026

    @mikependon
    OwnerAuthor

    @rhuijben hi, may I know when can you port some of your versions to main? And while you are doing that, I will do some bug hunting from the issue list.

  14. rhuijben commented on Sep 13, 2026

    @rhuijben
    Collaborator

    Sorry, can't actively work on this right now. Tried to move some info in that report so somebody else can (use some ai to) extract it from my codebase.

  15. mikependon commented on Sep 20, 2026

    @mikependon
    OwnerAuthor

    Hi All, I have supported this via PropertyHandlers as I stick on the original plan to not impacting the existing architecture. In this PR (or issue #1342), you will that many common and DB provider specific Property Handlers has been introduced.

    You will a lot on our documentation at https://repodb.net/propertyhandler/jsontoentitypropertyhandler/.

    Basically, the use-case here can be covered by JSON to TEntity handling (vice-versa).

  16. sanirr commented on Oct 20, 2026

    @sanirr

    Hi @mikependon
    We need to update a few regular columns and replace only one key of a jsonb column, keeping its other keys. Today we use raw SQL:

    UPDATE {TABLE}
    SET {COLUMN1} = @{VALUE1},
        COLUMN2 = jsonb_set(COALESCE(COLUMN2, '{}'::jsonb), '{Tags}', @Tags::jsonb, true)
    WHERE {COLUMN3} = @{VALUE3}
    

    Is there a typed way to do this in RepoDB, e.g. UpdateAsync with the regular fields plus a partial JSON update for the jsonb column?

  17. mikependon commented on Oct 20, 2026

    @mikependon
    OwnerAuthor

    Not directly JSON targeting, but you can do the trick via Propery Handler. Have you tried that already?

    With property handlers, you handle in C# how to hydrate and pass the contents in/out of model.

  18. AntyaDev commented on Oct 21, 2026

    @AntyaDev

    @mikependon Does PropertyHandler help filter by JSON fields? From what I see, it only helps with mapping, but you still can't write statically typed queries.

  19. mikependon commented on Oct 23, 2026

    @mikependon
    OwnerAuthor

    @sanirr and @AntyaDev - I fully supported this use case with property handler already. You can use the JsonToEntityPropertyHandler for this case.

    Disclaimer: With property handler, it follows the overall architecture of RepoDB.

    See sample below for clarity and how to use it cleanly.

    using RepoDb;
    using RepoDb.PropertyHandlers;
    
    public class ShippingAddress
    {
        public string Street { get; set; } = "";
    
        public string City { get; set; } = "";
    
        public string Country { get; set; } = "";
    }
    
    public class Order
    {
        public string OrderNumber { get; set; } = "";
    
        public decimal TotalAmount { get; set; }
    
        public ShippingAddress ShippingAddress { get; set; } = new();
    }
    
    public class Customer
    {
        public int Id { get; set; }
    
        public string Name { get; set; } = "";
    
        public Order? Order { get; set; }
    }

    Create a new record.

    using Microsoft.Data.SqlClient;
    using RepoDb;
    
    var connectionString = "YOUR_CONNECTION_STRING";
    using var connection = new SqlConnection(connectionString);
    
    var customer = new Customer
    {
        Name = "Michael",
        Order = new Order
        {
            OrderNumber = "ORD-1001",
            TotalAmount = 1500.00m,
            ShippingAddress = new ShippingAddress
            {
                Street = "Main Street 123",
                City = "Copenhagen",
                Country = "Denmark"
            }
        }
    };
    
    // Insert the customer
    var customerId = connection.Insert<Customer, int>(customer);
    
    Console.WriteLine($"Inserted Customer ID: {customerId}");

    The order column will contain the following JSON value.

    {
      "OrderNumber": "ORD-1001",
      "TotalAmount": 1500.00,
      "ShippingAddress": {
        "Street": "Main Street 123",
        "City": "Copenhagen",
        "Country": "Denmark"
      }
    }

    You can query it like below.

    var customer = connection.Query<Customer>(
        c => c.Id == customerId
    ).FirstOrDefault();
    
    if (customer?.Order is not null)
    {
        Console.WriteLine(customer.Name);
        Console.WriteLine(customer.Order.OrderNumber);
        Console.WriteLine(customer.Order.TotalAmount);
        Console.WriteLine(customer.Order.ShippingAddress.City);
    }

    You can also retrieve and update it like below.

    // Retrieve the customer
    var customer = connection.Query<Customer>(
        c => c.Id == customerId
    ).FirstOrDefault();
    
    if (customer?.Order is not null)
    {
        // Modify the Order properties
        customer.Order.OrderNumber = "ORD-1002";
        customer.Order.TotalAmount = 2500.00m;
    
        // Modify a nested child property
        customer.Order.ShippingAddress.Street = "New Street 456";
        customer.Order.ShippingAddress.City = "Gentofte";
    
        // Save the entire Customer
        var affectedRows = connection.Update(customer);
    
        Console.WriteLine($"Updated rows: {affectedRows}");
    }

    Just register it like below.

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

    But I agree with you @AntyaDev that it is only the mapping/hydration that works to this. I can introduce a JsonQueryField for you that is also passable to the Func for filtering.

  20. AntyaDev commented on Oct 23, 2026

    @AntyaDev

    @mikependon I think JsonQueryField can help, but I'm still not 100% sure I understand how you can patch/update the record without fetching it. Most of our cases are just updates without fully hydrating the entity in memory.

  21. mikependon commented on Oct 23, 2026

    @mikependon
    OwnerAuthor

    @AntyaDev let me think of this, and probably will just wait for @rhuijben's fork from his branch. I just released today the v1.17.0 with only the property handler support. I am planning to end the v1.X in the v1.17.0 as I am moving to v2.0 already, but this one is requires a movement to v1.18.0. Are you able to wait for v2.0, and for now use the RAW? I will spend time taking the fork out from Rhuiben's fork.

  22. AntyaDev commented on Oct 23, 2026

    @AntyaDev

    @mikependon, sure, no worries. It can wait :)

    I just wanted to say that the JSON story is very common in the modern SQL world. I forget when I designed tables in a relational model with N layers of JOINS (it makes query execution slow, not to mention all the migration headaches). Today I usually have a table with a few columns for mandatory filtering (common columns like ID, ProjectId, Created, LastUpdated) and the rest is just JSON.
    I really like the type-safe experience of writing queries, and this is where RepoDB is super cool! That said, working with JSON still requires a few extra steps and doesn’t quite feel like a first-class experience yet. Not sure if this helps, but I wanted to share this context in case it informs future improvements.

  23. mikependon commented on Oct 23, 2026

    @mikependon
    OwnerAuthor

    Definitely. Thanks for raising that @AntyaDev. I will revert with @rhuijben about his availability of pushing his work to the core. But, will definitely include the JSON support to the v2.0 on the model level, not just handler.

  24. mikependon commented on Nov 11, 2026

    @mikependon
    OwnerAuthor

    Hi @rhuijben, how are you? I hope that everything is well on your end. I made a promise to support JSON. I want to have near-zero deviations from your implementation. Will you be able to help me move the capabilities from your fork towards RepoDB master as the upstream branch? I will work on this within the week if this will never move. Thanks!

  25. mikependon commented on Nov 11, 2026

    @mikependon
    OwnerAuthor

    I have my AI helped me analyze this 'https://github.com/rhuijben/RepoDB' ait is now quite far from where we are. I am thinking if we could start from scratch or push for migrating from fork. There are major risks to do this on current main line,

    image

    I also see some code placements that requires refactoring, especially the BaseDbSetting should only contain properties, not functions. Although this is small.

    Let me see how can I approach this JSON thing.

  26. mikependon commented on Nov 11, 2026

    @mikependon
    OwnerAuthor

    I am struggling a bit on this to make a proper balance, but I will approach it with below.

    • Create the same experience of Test Suites that will hopefully follow the conventions of Rhuiben's fork implementation.
    • Use AI models to analyze the fork line with the above intention.
    • Then implement the things in RepoDB completely independent from the fork's code base. The reason is above, the huge differences from the fork compared to the main. We cannot do 1-2-1 copy of the code now. (Version 2.0 is merged on Main and my v1.17.x is on the branch)
    • Ensure that all Test Suites are green.

    No promise about the same experience of API, but it is with best stretch effort.

  27. mikependon commented on Nov 11, 2026

    @mikependon
    OwnerAuthor

    Examined the code base and came-up with the same proposal of APIs from fork.

    issue-1312-json-crud-sample.md

  28. added
    fixed
    on Nov 13, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

enhancementfixedrequest

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions