I have an order with specific data. Orders stores in dbo.Orders table which have SpecificData field (nvarchar(max)) for json-data. I use EF Code first. For JSON_VALUE I wrote DBFunction translation using this answer (https://stackoverflow.com/a/50490674/1411598) but I faced with a problem when I tried to add WHERE condition with INT type.
if (specificFilter.RegionIds != null && specificFilter.RegionIds.Count() > 0)
{
query = query.Where(g => specificFilter.RegionIds.Contains(DbFunc.JsonValue(g.specificData, "$.RegionId")));
}
Because JsonValue function return only string I cannot add clause with "contains". Think a little bit I try to write convert UDF function and translate to EF object. Here is my code:
if (specificFilter.RegionIds != null && specificFilter.RegionIds.Count() > 0)
{
query = query.Where(g => specificFilter.RegionIds.Contains(DbFunc.ConvertToInt(DbFunc.JsonValue(g.specificData, "$.RegionId"))));
}
UDF is very simple
CREATE FUNCTION [dbo].[ConvertToInt] (@value nvarchar(100))
returns int
AS
BEGIN
return convert(INT, @value)
END
It's works fine, but query is too slow:
WHERE (0 = [Extent1].[Status])
AND ([dbo].[ConvertToInt](JSON_VALUE([Extent1].[specificData], N''$.RegionId'')) IN (1))
It's bad because if I have a lot of rows query works very slow (UDF runs for each row)
So, can you help me to find the solution? I want to finally get such query:
WHERE (0 = [Extent1].[Status])
AND (CAST(JSON_VALUE([Extent1].[specificData], N''$.RegionId'') as int) IN (1))
By the other words can I translate CAST or CONVER function in EF DBFunction? Or may be there are some other ways?