【发布时间】:2019-10-23 04:12:18
【问题描述】:
我正在使用How to write DbFunction's translation 中的技术映射JSON_VALUE。由于并非 JSON 中的所有值都是字符串,因此有时需要进行转换。
转换为int时,一切正常:
var results = context.Set<SampleTable>()
.Where(t1 => Convert.ToInt32(
JsonExtensions.JsonValue(t1.SampleJson, "$.samplePath.sampleInt")) > 1);
.ToList();
生成的 SQL 是:
SELECT *
FROM [SampleTable] AS [t1]
WHERE (CONVERT(int, JSON_VALUE([t1].[SampleJson], N'$.samplePath.sampleInt')) > 1)
但是,当转换为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();
不是被映射,而是直接调用JsonValue,导致如下异常:
System.NotSupportedException H结果=0x80131515 Message=不支持指定的方法。 堆栈跟踪: 在 JsonExtensions.JsonValue(字符串列,字符串路径) 在 System.Linq.Enumerable.WhereEnumerableIterator
1.MoveNext() at Microsoft.EntityFrameworkCore.Query.Internal.LinqOperatorProvider.<_TrackEntities>d__172.MoveNext() 在 Microsoft.EntityFrameworkCore.Query.Internal.LinqOperatorProvider.ExceptionInterceptor`1.EnumeratorExceptionInterceptor.MoveNext()
为什么DateTime 的行为与int 不同?我该怎么做才能使DateTime 正常工作?
【问题讨论】:
标签: c# json sql-server entity-framework-core ef-core-2.2