Skip to content

Map JSON values stored in database to EF properties #4021

Closed

Description

@JocaPC

SQL Server, PostgreSQL, MySQL, and Oracle databases enable developers to store JSON in columns and use values from JSON documents in queries. As an example, we can create product table with few fixed columns and variable information stored as JSON:

Product[id,title,decription,datecreated,info]

info column can contain JSON text. Use cases are:

  1. I can put different non-standard information about products in JSON column as a set of key:value pairs in JSON column, e.g. {"color":"red","price":35.99,"status":1}.
  2. I can have new kind of single table inheritance where I can put all properties specific to some leaf classes as a bag of key:values instead of additional columns.

In SQL Server/Oracle we can use JSON_VALUE function to read JSON values from JSN column by keys, e.g.:

SELECT id, title,
       json_value(info,'$.price'),json_value(info,'$.color'),json_value(info,'$.status')
FROM product

PostgreSQL has ->> operator and MySQL has json_extract function that are similar.

Problem

Currently, JSON fields can be mapped to entities in entity framework as string properties and we can parse them using Json.Net library. It would be good if we could map properties in EF model to (JSON text+path).

Proposal

  1. Basic - Could we map property from EF model to string column that contains text and specify path of value in JSON (e.g. price, status) ? EF can extract json value on JSON path and populate property in EF model with proper type casting.
  2. Medium - Enable updates of properties mapped to json value. If some EF property that is mapped to JSON values is updated, EF could format all of them as JSON and save them back in the in JSON column.
  3. Advanced - Enable LINQ support over JSON properties. If we use Select(obj=>obj.price), or Where(obj => obj.price < 100) in LINQ queries, these predicates could be transformed to JSON_VALUE for SQL Server/Oracle, -> for PostgreSQL. This way we will be able to query JSON values directly from EF.

edited by @smitpatel on 16th March 2018

You can use JSON_VALUE function using user defined function feature in EF Core 2.0
#11295 (comment) explains how to do it for SqlServer.

Some open questions/possible subtasks:

  • Partial updates to JSON documents (would likely require modeling as owned entities)
  • Allow configuring JsonSerializationOptions to customize JSON property name etc., on a property-by-property basis (but also allow some bulk configuration default?)
  • Use or allow using the new System.Text.Json source generator introduced in .NET 6.0?
  • Indexes should probably out of scope of general relational support, as support differs considerably across databases.

Issues

Activity

  1. divega commented on Dec 9, 2015

    @divega
    Contributor

    @JocaPC We are of course busy completing more basic functionality than this at the moment but eventually I would love us to enable all of this. BTW, I think providing a way to declare indexes for values in the JSON payload (so that those queries can be optmized) would also be nice.

  2. added this to the Backlog milestone on Dec 9, 2015
  3. gdoron commented on Feb 29, 2016

    @gdoron

    @rowanmiller
    It would be helpful and user friendly if we could add to our POCO a dynamic property and through the modelbuilder mark it as JSON (modelbuilder.Entity<Product>().Property(x=> x.CustomFields).AsJson() where CustomFields is dynamic/ ExpandoObject).

    And then we will be able to nicely query the dynamic object like:

    context.Products.Where(x=> x.InsertDate > DateTime.Now && x.CustomFields.Retailer.Name == "Doron")
    
    // Or 
    context.Products.Where(x=> x.InsertDate > DateTime.Now && 
                               x.CustomFields.Retailer.Items.Contains("Foo"))
    

    Though I'm just not sure how indexing will work in SQL-Server 2016 for JSON columns @JocaPC

    OData is using something similar with Open Types and it's intuitive and very easy to use.

  4. omric-axonize commented on Feb 29, 2016

    @omric-axonize

    OData Open Type story sounds like a perfect fit to SQL-Server 2016 + EF Core!

  5. JocaPC commented on Feb 29, 2016

    @JocaPC
    Author

    You can add index on computed column that exposes JSON value:

    1. Create non-persisted computed column with expression JSON_VALUE(jsonCol, '$.Retailer.Name')
    2. Create index on that computed column

    Original queries don't need to be rewritten. When SQL Server finds a query that uses JSON_VALUE and if path in JSON_VALUE matches computed column that has index, it will use indexing. See
    https://msdn.microsoft.com/en-us/library/mt612798.aspx

  6. erichexter commented on Apr 2, 2016

    @erichexter

    I would like to see this support.

  7. DaveSlinn commented on Apr 6, 2016

    @DaveSlinn

    My team is currently investigating EF for a new application we are undertaking and I was hoping to use this very feature. If we were so inclined to invest in working on this feature, for our own selfish needs, would that be worthwhile contributing?

  8. ikourfaln commented on Jun 16, 2016

    @ikourfaln

    We realy need this functionality

  9. ikourfaln commented on Jun 16, 2016

    @ikourfaln

    At the moment, I think that we can just use FromSql function to execute raw SQL and include JSON_VALUE.
    example:

    var contacts = _context.Contacts.FromSql("SELECT Id, Name, Address, City, State, Zip " +
                                            "FROM Contacts " +
                                            "WHERE JSON_VALUE(Info, '$.Moniker') = @p1", moniker1);
  10. soycabanillas commented on Jul 31, 2016

    @soycabanillas

    My two cents (what I'm doing for now) for proposal 1:

    I configure my entities this way:

    public class ConfigCTransfer : EntityMappingConfiguration<CTransfer>
    {
        public override void Map(EntityTypeBuilder<CTransfer> entity)
        {
            entity.HasJsonValue(x => x.Serialized, y => y.Data.Status, z => z.FStatus);
        }
    }
    

    x.Serialized is the JSON/text field.
    y.Data is the object that is serialized into Serialized. Status is just a property of Data.
    z.FStatus is the column where I'm going to store the value of y.Data.Status.

    the heavyweight is done by the HasJson extension method. I include the code (not a clean one) for copy paste, but the important thing here is that I'm setting the FStatus property as a computed column, as @JocaPC commented.

        public static void HasJsonValue<T, U>(this EntityTypeBuilder<T> value, Expression<Func<T, string>> jsonFieldExpr, Expression<Func<T, U>> jsonPathExpr, Expression<Func<T, U>> dataFieldExpr) where T : class
        {
            var jsonPathSegments = PathFromExpression(jsonPathExpr);
            jsonPathSegments.RemoveAt(0);
            var jsonPath = string.Join(".", jsonPathSegments);
    
            var jsonFieldSegments = PathFromExpression(jsonFieldExpr);
            var jsonField = string.Join(".", jsonFieldSegments);
    
            var sqlDataType = new SqlServerTypeMapper().FindMapping(typeof(U));
            //var typeName =  sqlDataType.DefaultTypeName;
            var typeName = sqlDataType.StoreType;
            var property = value.Property(dataFieldExpr);
            var isNullable = property.Metadata.IsNullable;
            var isForeignKey = property.Metadata.IsForeignKey();
            var maxLength = property.Metadata.GetMaxLength();
            if (maxLength != null) typeName = typeName.Replace("(max)", $"({maxLength.Value})");
            var columnDefinition = $"CAST((json_value([{jsonField}],'$.{jsonPath}')) AS {typeName})";
            if (isNullable == false || isForeignKey) columnDefinition = columnDefinition + " PERSISTED";
            if (isNullable == false) columnDefinition = columnDefinition + " NOT NULL";
            value.Property(dataFieldExpr).HasComputedColumnSql(columnDefinition);
        }
    
        //For other solutions, see:
        //http://stackoverflow.com/questions/1667408/c-getting-names-of-properties-in-a-chain-from-lambda-expression
        //and
        //http://stackoverflow.com/questions/2789504/get-the-property-as-a-string-from-an-expressionfunctmodel-tproperty
        public static List<string> PathFromExpression<T, P>(Expression<Func<T, P>> expr)
        {
            var result = new List<string>();
            MemberExpression me;
            switch (expr.Body.NodeType)
            {
                case ExpressionType.Convert:
                case ExpressionType.ConvertChecked:
                    var ue = expr.Body as UnaryExpression;
                    me = ((ue != null) ? ue.Operand : null) as MemberExpression;
                    break;
                default:
                    me = expr.Body as MemberExpression;
                    break;
            }
    
            while (me != null)
            {
                string propertyName = me.Member.Name;
                //Type propertyType = me.Type;
                result.Add(propertyName);
                //Console.WriteLine(propertyName + ": " + propertyType);
    
                me = me.Expression as MemberExpression;
            }
            result.Reverse();
            return result;
        }
    

    The EntityMappingConfiguration thing is just a friendly way of having the configuration of an entity in its own class. You can see the implementation and the discussion here:
    https://github.com/aspnet/EntityFramework/issues/2805#issuecomment-218548872

    If anyone needs helps with this, just ask me.

    This has several limitations, though, at least:
    1 - The properties are computed columns. The value will not be set until the entity is saved. But it will be of use for indexing.
    2 - It doesn't support polymorphism, at least not in an easy/clear way. You can't use the same data for different entities... or I haven't found the way:

    a - You can't use different classes to point to the very same table #6001
    b - You can't use different classes to point to the very same field #240

    Sorry if something about my conclusions is not completely accurate. There are others more capable of validating them. I just tried to expose my experience so far.

  11. soycabanillas commented on Jul 31, 2016

    @soycabanillas

    And...

    3 - This solution only supports SQL Server. No support for in memory database.

  12. bjorn-ali-goransson commented on Aug 2, 2016

    @bjorn-ali-goransson

    I think the comment of @ikourfaln is superiour (and simplest to implement, ie already done) in combination with the flexible mapping idea.

  13. ma3yta commented on Sep 28, 2016

    @ma3yta

    When it will be done?

  14. ikourfaln commented on Sep 29, 2016

    @ikourfaln

    @ma3yta 😞
    not yet decided. must be moved from Backlog to a Milestone

  15. 106 remaining items

  16. removed their assignment
    on Aug 14, 2022
  17. maumar commented on Aug 23, 2022

    @maumar
    Contributor

    initial support is now checked in: 4018482 and 0577a3a, closing this issue

  18. modified the milestones: 7.0.0, on Aug 23, 2022
  19. MoazAlkharfan commented on Sep 12, 2022

    @MoazAlkharfan

    Will there be support for JsonSerializationOptions?

  20. maumar commented on Sep 26, 2022

    @maumar
    Contributor

    @MoazAlkharfan eventually, we have #28815 to track this

  21. modified the milestones: , 7.0.0 on Nov 5, 2022
  22. added theissue type on Jun 15, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Projects

No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions