Skip to content

How to write DbFunction's translation? #11295

Closed as not planned
Closed as not planned

Description

@Kation

When we use ModelBuilder.HasDbFunction to add a database function to model
It generate the SQL with QUOTE char all of the arguments
With SQL Server 2016, there is a JSON_VALUE function
It's require first argument to be column without QUOTE, and second argument not be a parameter.

I wrote a test to solve first question but a bug exist.

Write a static method

public static class JsonExtensions
{
    public static string JsonValue(string column, string path)
    {
        throw new NotSupportedException();
    }
}

Write a expression translate method

public static class JsonExpressionTranslator
{
    public static Expression Translate(IReadOnlyCollection<Expression> expressions)
    {
        var items = expressions.ToArray();
        return new JsonExpression(items[0], items[1]);
    }
}

Write a json expression

public class JsonExpression : Expression
{
    public JsonExpression(Expression column, Expression path)
    {
        Column = column;
        Path = path;
    }

    public override ExpressionType NodeType => ExpressionType.Extension;

    public Expression Column { get; private set; }

    public Expression Path { get; private set; }

    protected override Expression Accept(ExpressionVisitor visitor)
    {
        if (visitor is ISqlExpressionVisitor specificVisitor)
        {
            string sql = $"JSON_VALUE([{Column.ToString().Trim('"')}],";
            specificVisitor.VisitSqlFragment(new SqlFragmentExpression(sql));
            visitor.Visit(Path);
            sql = ")";
            return specificVisitor.VisitSqlFragment(new SqlFragmentExpression(sql));
        }
        else
            return base.Accept(visitor);
    }

    protected override Expression VisitChildren(ExpressionVisitor visitor)
    {
        return new JsonExpression(visitor.Visit(Column), visitor.Visit(Path));
    }

    public override Type Type => typeof(string);

    public override string ToString() => $"JSON_VALUE([{Column.ToString().Trim('"')}], '{Path.ToString().Trim('"')}')";
}

Configure model

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
    modelBuilder.HasDbFunction(typeof(JsonExtensions).GetMethod("JsonValue"), options => options.HasTranslation(JsonExpressionTranslator.Translate));
}

Write query

var path = "$.Filter"; //this argument used to be dynamic
var result = dbContext.Items.Where(t => JsonExtensions.JsonValue("Values", path).ToArray();

It came out sql with
JSON_VALUE([Values],@__path_1)
And column name has no table relate, path is a parameter

-- How to generate sql without QUOTE?
-- How to generate sql that argument is not a PARAMETER?

Activity

  1. ajcvickers commented on Mar 16, 2018

    @ajcvickers
    Contributor

    @smitpatel will provide some guidance here.

  2. added this to the 2.1.0 milestone on Mar 16, 2018
  3. ajcvickers commented on Mar 16, 2018

    @ajcvickers
    Contributor

    @smitpatel Also, if this can be done in a way that we get docs out of it then all the better! /cc @divega

  4. smitpatel commented on Mar 16, 2018

    @smitpatel
    Contributor

    @Kation
    You actually does not need so much of code to use JSON_VALUE function.
    Based on documentation of function,

    • 1st argument has to be string type. It can be any expression. You can pass literal string/parameter or use column. EF Core will take care of it automatically based on whatever value you pass in.
    • 2nd argument has to be literal string at present. It cannot be parameter (this requirement is going away in SqlServer 2017). Since EF generates parameter for closure variable it is giving you 2nd error. So you just need to tell EF not to create parameter by using NotParameterized attribute on the parameter of your function.

    So in your function definition, all you have to configure is its name & schema in database.
    The overall code you need to add is as follows

    public static class JsonExtensions
    {
        public static string JsonValue(string column, [NotParameterized] string path)
        {
            throw new NotSupportedException();
        }
    }

    And in your OnModelCreating

    modelBuilder.HasDbFunction(typeof(JsonExtensions).GetMethod(nameof(JsonExtensions.JsonValue)))
        .HasName("JSON_VALUE") // function name in server
        .HasSchema(""); // empty string since in built functions has no schema

    Starting from 3.0, using followign in OnModelCreating

    protected override void OnModelCreating(ModelBuilder modelBuilder)
            {
                // Configure model
                modelBuilder.HasDbFunction(typeof(JsonExtensions).GetMethod(nameof(JsonExtensions.JsonValue)))
                    .HasTranslation(e => SqlFunctionExpression.Create(
                        "JSON_VALUE", e, typeof(string), null));
            }

    With above code added, for query like where t.Log is column containing JSON

    var path = "$.Filter"; //this argument used to be dynamic
    var result = db.Blogs.Select(t => JsonExtensions.JsonValue(t.Log, path)).ToArray();

    generates SQL which works correctly for me in SqlServer 2016

          SELECT JSON_VALUE([t].[Log], N'$.Filter')
          FROM [Blogs] AS [t]

    Let me know if you still face issues with translation.

  5. removed this from the 2.1.0 milestone on Mar 16, 2018
  6. cleftheris commented on Jun 6, 2018

    @cleftheris

    @smitpatel Just an addition to your comment above. In case someone uses a ValueConverter on the Blog mapping the Log property like so

    builder.Property(x => x.Log).HasConversion(new ValueConverter<object, string>(
    v => v != null ? JsonConvert.SerializeObject(v, serializerSettings) : null,
    v => v != null ? JsonConvert.DeserializeObject<object>(v) : null));

    then the on the Log property will not be of type String .

    public class Blog
    {
        public int BlogId { get; set; }
    
        public string Url { get; set; }
        
        public object Log { get; set; }
    }

    In this case the query will continue to translate to valid SQL if we cast the object back to string

    var path = "$.Filter"; //this argument used to be dynamic
    var result = db.Blogs.Select(t => JsonExtensions.JsonValue((string)t.Log, path)).ToArray();

    By the way I tried this on a where clause and it still works!

  7. CoskunSunali commented on Dec 21, 2018

    @CoskunSunali

    For anyone looking around here in the future, be cautious using the JSON_VALUE function as it is a scalar function and will play naughty when the value is longer than 4000 chars.

    https://docs.microsoft.com/en-us/sql/t-sql/functions/json-value-transact-sql?view=sql-server-2017

    Extracts a scalar value from a JSON string.

    Return Value
    Returns a single text value of type nvarchar(4000). The collation of the returned value is the same as the collation of the input expression.

    If the value is greater than 4000 characters:

    • In lax mode, JSON_VALUE returns null.

    • In strict mode, JSON_VALUE returns an error.

    If you have to return scalar values greater than 4000 characters, use OPENJSON instead of JSON_VALUE.

  8. yechao59228866 commented on Jun 25, 2019

    @yechao59228866

    @Kation
    You actually does not need so much of code to use JSON_VALUE function.
    Based on documentation of function,

    • 1st argument has to be string type. It can be any expression. You can pass literal string/parameter or use column. EF Core will take care of it automatically based on whatever value you pass in.
    • 2nd argument has to be literal string at present. It cannot be parameter (this requirement is going away in SqlServer 2017). Since EF generates parameter for closure variable it is giving you 2nd error. So you just need to tell EF not to create parameter by using NotParameterized attribute on the parameter of your function.

    So in your function definition, all you have to configure is its name & schema in database.
    The overall code you need to add is as follows

    public static class JsonExtensions
    {
        public static string JsonValue(string column, [NotParameterized] string path)
        {
            throw new NotSupportedException();
        }
    }

    And in your OnModelCreating

    modelBuilder.HasDbFunction(typeof(JsonExtensions).GetMethod(nameof(JsonExtensions.JsonValue)))
        .HasName("JSON_VALUE") // function name in server
        .HasSchema(""); // empty string since in built functions has no schema

    With above code added, for query like where t.Log is column containing JSON

    var path = "$.Filter"; //this argument used to be dynamic
    var result = db.Blogs.Select(t => JsonExtensions.JsonValue(t.Log, path)).ToArray();

    generates SQL which works correctly for me in SqlServer 2016

          SELECT JSON_VALUE([t].[Log], N'$.Filter')
          FROM [Blogs] AS [t]

    Let me know if you still face issues with translation.

    the program is dead after throw new NotSupportedException()

  9. wsaeed commented on Jul 15, 2019

    @wsaeed

    EF Core by default uses decimal(18, 2) for Convert.ToDecimal. I need to use different precision and scale for my conversion. For this, I have defined a DB function as below and also register it during model creation.

    [DbFunction("CONVERT", Schema = "")]
    public static decimal Convert([NotParameterized]string dataType, double value)
    {
             throw new NotImplementedException();
    }

    I am calling the above function in my query.

    where DbFunctions.Convert("DECIMAL(31, 6)", sale.Discount/ 100) > 0

    Here Amount is a double value (The database is designed 20 years back, so I can't change the datatype)

    SQL generated is

    WHERE CONVERT(N'DECIMAL(31, 6)', sale.Discount / 100)  > 0,

    Note: The quotes are generated around DECIMAL, instead of a SQL literal.

    Any ideas?

  10. yechao59228866 commented on Jul 15, 2019

    @yechao59228866
  11. 21 remaining items

  12. elkami commented on Mar 7, 2020

    @elkami

    Your method is outside of your DbContext, which is why you do not register automatically.

    thanks a lot, this comment help me a lot, because i was my prototype funcitonality on LinqPad, working like a charm, when i put that on my project, cannot translate DbFunction, and try the WeinhanLi example without success, i think something is missing there. where is JsonValue method?
    now i going to research who can this things work on a unit test ef memory environment

  13. rogerfar commented on Nov 26, 2020

    @rogerfar

    I have been writing my JSON_VALUE like this, which I found is the only way that works:

                modelBuilder.HasDbFunction(typeof(DataContext).GetMethod(nameof(JsonValue)))
                            .HasTranslation(e => SqlFunctionExpression.Create("JSON_VALUE", e, typeof(String), null))
                            .HasParameter("column")
                            .HasStoreType("nvarchar(max)");
    
            public static String JsonValue(Object column, String path)
            {
                throw new NotSupportedException();
            }
    

    But now SqlFunctionExpression.Create is obsolete I'm trying to rewrite it to new SqlFunctionExpression, but can't work out the parameters excactly.

  14. inexuscore commented on Dec 1, 2020

    @inexuscore

    @rogerfar Although your code works, SqlFunctionExpression.Create() has been marked as obsolete in .NET 5.0. It says use new SqlFunctionExpression() with appropriate arguments but I can't get it to work. The last constructor argument of type RelationalTypeMapping is confusing and I don't know what to do with it. Any ideas?

  15. inexuscore commented on Dec 1, 2020

    @inexuscore

    @Kation
    You actually does not need so much of code to use JSON_VALUE function.
    Based on documentation of function,

    • 1st argument has to be string type. It can be any expression. You can pass literal string/parameter or use column. EF Core will take care of it automatically based on whatever value you pass in.
    • 2nd argument has to be literal string at present. It cannot be parameter (this requirement is going away in SqlServer 2017). Since EF generates parameter for closure variable it is giving you 2nd error. So you just need to tell EF not to create parameter by using NotParameterized attribute on the parameter of your function.

    So in your function definition, all you have to configure is its name & schema in database.
    The overall code you need to add is as follows

    public static class JsonExtensions
    {
        public static string JsonValue(string column, [NotParameterized] string path)
        {
            throw new NotSupportedException();
        }
    }

    And in your OnModelCreating

    modelBuilder.HasDbFunction(typeof(JsonExtensions).GetMethod(nameof(JsonExtensions.JsonValue)))
        .HasName("JSON_VALUE") // function name in server
        .HasSchema(""); // empty string since in built functions has no schema

    Starting from 3.0, using followign in OnModelCreating

    protected override void OnModelCreating(ModelBuilder modelBuilder)
            {
                // Configure model
                modelBuilder.HasDbFunction(typeof(JsonExtensions).GetMethod(nameof(JsonExtensions.JsonValue)))
                    .HasTranslation(e => SqlFunctionExpression.Create(
                        "JSON_VALUE", e, typeof(string), null));
            }

    With above code added, for query like where t.Log is column containing JSON

    var path = "$.Filter"; //this argument used to be dynamic
    var result = db.Blogs.Select(t => JsonExtensions.JsonValue(t.Log, path)).ToArray();

    generates SQL which works correctly for me in SqlServer 2016

          SELECT JSON_VALUE([t].[Log], N'$.Filter')
          FROM [Blogs] AS [t]

    Let me know if you still face issues with translation.

    SqlFunctionExpression.Create("JSON_VALUE", args, typeof(string), null) is deprecated. I've been struggling with this for hours and it feels dumb because I know it's a quick fix (LOL). SqlFunctionExpression.Create() is obsolete in .NET 5, any ideas on how to rewrite this and make VS stop complaining?

  16. smitpatel commented on Dec 1, 2020

    @smitpatel
    Contributor
    new SqlFunctionExpression(
        "JSON_VALUE",
        args,
        nullable: true,
        argumentsPropagateNullability: new [] { false, false },
        typeof(string),
        null)
  17. rogerfar commented on Dec 1, 2020

    @rogerfar

    Thanks @smitpatel this works for me.

  18. inexuscore commented on Dec 2, 2020

    @inexuscore

    @smitpatel Ah! I see. It was argumentsPropagateNullability that I was missing. Excellent! Thank you very much, works.

  19. rogerfar commented on Dec 24, 2020

    @rogerfar

    @smitpatel I have tried your implementation as following:

                modelBuilder.HasDbFunction(typeof(DataContext).GetMethod(nameof(JsonValue)))
                            .HasTranslation(e => new SqlFunctionExpression("JSON_VALUE", e, true, new [] { true, false }, typeof(String), null))
                            .HasParameter("column")
                            .HasStoreType("nvarchar(max)");
    

    Instead of

                modelBuilder.HasDbFunction(typeof(DataContext).GetMethod(nameof(JsonValue)))
                            .HasTranslation(e => SqlFunctionExpression.Create("JSON_VALUE", e, typeof(String), null))
                            .HasParameter("column")
                            .HasStoreType("nvarchar(max)");
    

    But it's not giving the same results.

    When I run this query:

    _dataContext.Tickets.Where(ticket => DataContext.JsonValue(ticket.MetaData, "$.approvedOn") == null)
    

    I get this result at the first option:

    SELECT * FROM [Tickets] AS [t] WHERE [t].[MetaData] IS NULL
    

    While I get this with the 2nd option:

    SELECT * FROM [Tickets] AS [t] WHERE JSON_VALUE([t].[MetaData], N'$.approvedOn') IS NULL
    
  20. smitpatel commented on Dec 28, 2020

    @smitpatel
    Contributor

    @rogerfar - Updated my comment. A slightly incorrect argument passed optimizes SQL that way. Essentially if column is null then value of function is going to be null but other way is not true (if function value is null then column must have been null).

  21. inexuscore commented on Dec 28, 2020

    @inexuscore

    @smitpatel Ah I see, the argumentsPropagateNullability now has { false, false }. Gotta test it in production but thank you.

  22. removed their assignment
    on Jan 12, 2022
  23. walapa-nl commented on Dec 1, 2024

    @walapa-nl

    new SqlFunctionExpression(
    "JSON_VALUE",
    args,
    nullable: true,
    argumentsPropagateNullability: new [] { false, false },
    typeof(string),
    null)

    Thanks a ton! Had to use this exact approach in EF Core 9 to get it working after migrating from EF Core 3.1.

    I do hope EF Core will ship with these functions out of the box, they are so useful and helpful, and I have to presume such a very common scenario; perhaps coming to a milestone in the future then.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions