简体   繁体   中英

Filter table with Json array column by integer value

In EF Core how can I efficiently check if text column of Json array contains any number from passed integer array using LINQ?

Example of table, where Id is integer type and Name and TypeJson are text

| Id  | Name       | TypeJson |
| --- | ---------- | -------- |
| 1   | Name One   | [1,2]    |
| 2   | Name Two   | [2,3]    |
| 3   | Name Three | [4,7]    |

In Postgresql I would have written something like this

SELECT *
FROM "Table"
WHERE translate("TypeJson", '[]','{}')::int[] && ARRAY[1, 7]

where the select would return 1 and 3 rows. I'd like to achieve same result by using LINQ functions. I tried using EF.Functions but didn't achieve much. My attempt

await _dbContect.Table
.Where(x => !string.IsNullOrEmpty(x.TypeJson ) && 
            EF.Functions.JsonContains(x.TypeJson , "[1]")
.ToListAsync();

But it produces error as column is type of text and not Json

System.InvalidOperationException: The EF JSON methods require a JSON parameter and none was found.

The entity:

public class Table
{
    public int Id { get; set; }

    public string Name { get; set; }

    public string TypeJson { get; set; }
}

Using FromSqlRaw() is not possible because there is already written code and would be preferable if I didn't have to rewrite whole code block.

As I found out my code had three main problems

await _dbContect.Table
    .Where(x => !string.IsNullOrEmpty(x.TypeJson) && 
                EF.Functions.JsonContains(x.TypeJson , "[1]")
    .ToListAsync();
  1. First of all I was using EF.Functions.JsonContains() function on text column which is not valid, json functions are deliberately written for jsonb type.
  2. After altering column type to jsonb , the second problem was using string function to check if jsonb column was null or empty which doesn't make sense and produces exception. Link to github issue
  3. The third problem was the parameter I tried to filter with "[1]" , integer needs to be passed as a JsonElement JsonSerializer.SerializeToElement(value); Link to github issue by ahanusa

Credits to @GuruStron for directing me to correct direction

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM