簡體   English   中英

按 integer 值過濾具有 Json 數組列的表

[英]Filter table with Json array column by integer value

在 EF Core 中,我如何有效地檢查 Json 數組的文本列是否包含使用 LINQ 傳遞的 integer 數組中的任何數字?

表格示例,其中Idinteger類型, NameTypeJsontext

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

在 Postgresql 我會寫這樣的東西

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

其中 select 將返回 1 和 3 行。 我想通過使用 LINQ 函數來實現相同的結果。 我嘗試使用EF.Functions但收效甚微。 我的嘗試

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

但它會產生錯誤,因為列是文本類型而不是 Json

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

實體:

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

    public string Name { get; set; }

    public string TypeJson { get; set; }
}

使用FromSqlRaw()是不可能的,因為已經編寫了代碼,如果我不必重寫整個代碼塊,那將是更好的選擇。

當我發現我的代碼存在三個主要問題時

await _dbContect.Table
    .Where(x => !string.IsNullOrEmpty(x.TypeJson) && 
                EF.Functions.JsonContains(x.TypeJson , "[1]")
    .ToListAsync();
  1. 首先,我在無效的文本列上使用EF.Functions.JsonContains() function,json 函數是故意為jsonb類型編寫的。
  2. 將列類型更改為jsonb后,第二個問題是使用字符串 function 檢查jsonb列是 null 還是空,這沒有意義並會產生異常。 github問題鏈接
  3. 第三個問題是我嘗試使用"[1]"過濾的參數,integer 需要作為 JsonElement JsonSerializer.SerializeToElement(value); 鏈接到 github issue by ahanusa

感謝@GuruStron 指導我正確的方向

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM