1

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.

1
  • Can you please share the entity setup? Commented Dec 6, 2022 at 20:24

1 Answer 1

2

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

Sign up to request clarification or add additional context in comments.

1 Comment

Glad you have resolved the issue!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.