Repository navigation
Closed as not planned
Labels
Description
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
ajcvickers commentedon Mar 16, 2018
@smitpatel will provide some guidance here.
ajcvickers commentedon Mar 16, 2018
@smitpatel Also, if this can be done in a way that we get docs out of it then all the better! /cc @divega
smitpatel commentedon Mar 16, 2018
@Kation
You actually does not need so much of code to use
JSON_VALUEfunction.Based on documentation of function,
NotParameterizedattribute 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
And in your OnModelCreating
Starting from 3.0, using followign in
OnModelCreatingWith above code added, for query like where t.Log is column containing JSON
generates SQL which works correctly for me in SqlServer 2016
Let me know if you still face issues with translation.
cleftheris commentedon Jun 6, 2018
@smitpatel Just an addition to your comment above. In case someone uses a
ValueConverteron the Blog mapping the Log property like sothen the on the
Logproperty will not be of typeString.In this case the query will continue to translate to valid SQL if we cast the object back to string
By the way I tried this on a where clause and it still works!
CoskunSunali commentedon Dec 21, 2018
For anyone looking around here in the future, be cautious using the
JSON_VALUEfunction 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
yechao59228866 commentedon Jun 25, 2019
the program is dead after throw new NotSupportedException()
wsaeed commentedon Jul 15, 2019
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.
I am calling the above function in my query.
Here Amount is a double value (The database is designed 20 years back, so I can't change the datatype)
SQL generated is
Note: The quotes are generated around DECIMAL, instead of a SQL literal.
Any ideas?
yechao59228866 commentedon Jul 15, 2019
21 remaining items
elkami commentedon Mar 7, 2020
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
rogerfar commentedon Nov 26, 2020
I have been writing my JSON_VALUE like this, which I found is the only way that works:
But now
SqlFunctionExpression.Createis obsolete I'm trying to rewrite it tonew SqlFunctionExpression, but can't work out the parameters excactly.inexuscore commentedon Dec 1, 2020
@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?
inexuscore commentedon Dec 1, 2020
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?smitpatel commentedon Dec 1, 2020
rogerfar commentedon Dec 1, 2020
Thanks @smitpatel this works for me.
inexuscore commentedon Dec 2, 2020
@smitpatel Ah! I see. It was argumentsPropagateNullability that I was missing. Excellent! Thank you very much, works.
rogerfar commentedon Dec 24, 2020
@smitpatel I have tried your implementation as following:
Instead of
But it's not giving the same results.
When I run this query:
I get this result at the first option:
While I get this with the 2nd option:
smitpatel commentedon Dec 28, 2020
@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).
inexuscore commentedon Dec 28, 2020
@smitpatel Ah I see, the argumentsPropagateNullability now has { false, false }. Gotta test it in production but thank you.
walapa-nl commentedon Dec 1, 2024
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.