![](/img/trans.png)
[英]How can I use SQL Server JSON_VALUE function in EF 6 Code First for classic .NET
[英]How can a JSON_VALUE be converted to a DateTime with EF Core 2.2?
我正在使用如何编写DbFunction的翻译中的技术映射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 HResult = 0x80131515 Message =不支持指定的方法。 StackTrace:位于System.Linq.Enumerable.WhereEnumerableIterator处于JsonExtensions.JsonValue(字符串列,字符串路径)处,
1.MoveNext() at Microsoft.EntityFrameworkCore.Query.Internal.LinqOperatorProvider.<_TrackEntities>d__17
处的2。 .Query.Internal.LinqOperatorProvider.ExceptionInterceptor`1.EnumeratorExceptionInterceptor.MoveNext()
为什么DateTime
行为与int
不同? 如何使DateTime
正常工作?
问题在于,并非所有的Convert
方法都受支持。
实际上,它们都不是标准支持的-EF Core允许数据库提供者根据自己的喜好添加CLR方法和成员转换器。 例如,SqlServer提供程序当前支持 ToByte
, ToDecimal
, ToDouble
, ToInt16
, ToInt32
, ToInt64
和ToString
。
这意味着没有数据库不可知的方式来执行服务器端转换。
由于您似乎正在使用SqlServer,因此,作为解决方法,我建议使用隐式数据转换(当前由SqlServer提供程序支持),方法是将我的答案中的“双重转换”技术用于类似的帖子 ,例如
.Where(t1 => (DateTime)(object)JsonExtensions.JsonValue(t1.SampleJson, "$.samplePath.sampleDate") >= date);
(object)
强制转换用于避免C#编译器错误。 在查询转换期间,将删除所有强制类型转换,并且SQL Server隐式数据转换最终将完成此工作。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.