相关疑难解决方法(0)

使用EF Core将表达式树转换为SQL

我们有一个列,其中JSON数据存储为字符串.读取此JSON数据并通过实现将其转换为IDictionary<string, object>.这一切都正常,直到我想要过滤它.仅在从数据库获取数据后才应用过滤.我们将拥有数百万条记录,因此这是不可接受的.我的过滤器被EF Core完全忽略为WHERE子句,因为它可能不知道如何解析MethodCallExpressions.

我正在寻找一种方法来尽可能接近我在下面使用表达式树的SQL查询.

我需要转换这个:

.Call System.Linq.Queryable.Where(
    .Constant<QueryTranslator`1[Setting]>(QueryTranslator`1[Setting]),
    '(.Lambda #Lambda1<System.Func`2[Setting,System.Boolean]>))

.Lambda #Lambda1<System.Func`2[Setting,System.Boolean]>(Setting $$it)
{
    ((System.Nullable`1[System.Int32]).If (
        $$it.Value != null && .Call ($$it.Value).ContainsKey("Name")
    ) {
        ($$it.Value).Item["Name"]
    } .Else {
        null
    } > (System.Nullable`1[System.Int32]).Constant<Microsoft.AspNet.OData.Query.Expressions.LinqParameterContainer+TypedLinqParameterContainer`1[System.Int32]>(Microsoft.AspNet.OData.Query.Expressions.LinqParameterContainer+TypedLinqParameterContainer`1[System.Int32]).TypedProperty)
    == .Constant<System.Nullable`1[System.Boolean]>(True)
}
Run Code Online (Sandbox Code Playgroud)

进入:

SELECT *
FROM [Setting]
WHERE JSON_VALUE([Value], 'lax $.Name') > 1; -- [Value_Name] > 1 is also fine
Run Code Online (Sandbox Code Playgroud)

随着ExpressionVisitor我已经成功地得到尽可能靠近WHERE [超值] ="东西",但字符串这只是工作和键名是缺乏.

c# entity-framework-core

5
推荐指数
1
解决办法
643
查看次数

如何使用 EF Core 2.2 将 JSON_VALUE 转换为 DateTime?

我正在JSON_VALUE使用How to write DbFunction's translation 中的技术进行映射。由于并非 JSON 中的所有值都是字符串,因此有时需要进行转换。

转换为 时int,一切正常:

var results = context.Set<SampleTable>()
    .Where(t1 => Convert.ToInt32(
        JsonExtensions.JsonValue(t1.SampleJson, "$.samplePath.sampleInt")) > 1);
    .ToList();
Run Code Online (Sandbox Code Playgroud)

生成的 SQL 是:

SELECT *
FROM [SampleTable] AS [t1]
WHERE (CONVERT(int, JSON_VALUE([t1].[SampleJson], N'$.samplePath.sampleInt')) > 1)
Run Code Online (Sandbox Code Playgroud)

但是,当转换为 时DateTime,它不起作用:

DateTime date = new DateTime(2019, 6, 1);
var results = context.Set<SampleTable>()
    .Where(t1 => Convert.ToDateTime(
        JsonExtensions.JsonValue(t1.SampleJson, "$.samplePath.sampleDate")) >= date);
    .ToList();
Run Code Online (Sandbox Code Playgroud)

不是被映射,而是JsonValue直接调用,导致如下异常:

System.NotSupportedException HResult=0x80131515 消息=不支持指定的方法。StackTrace:在 JsonExtensions.JsonValue(String column, String path) at System.Linq.Enumerable.WhereEnumerableIterator 1.MoveNext() at …

c# sql-server json entity-framework-core ef-core-2.2

4
推荐指数
1
解决办法
1991
查看次数