[英]Filter integer array of jsonb column in postgres using EF Core and NpgSql
[英]Filter table with Json array column by integer value
在 EF Core 中,我如何有效地檢查 Json 數組的文本列是否包含使用 LINQ 傳遞的 integer 數組中的任何數字?
表格示例,其中Id
為integer
類型, Name
和TypeJson
為text
| 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();
EF.Functions.JsonContains()
function,json 函數是故意為jsonb
類型編寫的。jsonb
后,第二個問題是使用字符串 function 檢查jsonb
列是 null 還是空,這沒有意義並會產生異常。 github問題鏈接"[1]"
過濾的參數,integer 需要作為 JsonElement JsonSerializer.SerializeToElement(value);
鏈接到 github issue by ahanusa感謝@GuruStron 指導我正確的方向
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.