首页 > 解决方案 > Npgsql.PostgresException (0x80004005): 42883: 运算符不存在: jsonb #> text

问题描述

我有以下 SQL 查询:

select distinct "Customers"."CustomerId"        as "CustomerId",
                "Customers"."FcmRegistrationId" as "FcmRegistrationId",
                "Customers"."FCMServerKey"      as "FCMServerKey",
                "Customers"."AppId"             as "AppId"
from "CustomerEvents"
         inner join "Customers" on "CustomerEvents"."CustomerId" = "Customers"."CustomerId"
where  "Customers"."AdvertiserId" = 16 and "Data" #> '{inner_id}' = '4249699';

它在我的 SQL 编辑器客户端(DataGrip)中运行良好。但是当我使用它时C#,我从这个问题的标题中得到了错误。

Npgsql.PostgresException (0x80004005): 42883: 运算符不存在: jsonb #> text

我将向您展示我的代码:

public class PartnerApiServices : IPartnerApiService
{
    private readonly ApplicationDbContext _applicationDbContext;

    public PartnerApiServices(ApplicationDbContext applicationDbContext)
    {
        _applicationDbContext = applicationDbContext;
    }

    public IQueryable<CustomerForPartnerApiServiceModel> GetCustomerBySearchField(Advertiser advertiser, string searchValue)
    {
        var rawSql = @"
            select distinct ""Customers"".""CustomerId""        as ""CustomerId"",
                            ""Customers"".""FcmRegistrationId"" as ""FcmRegistrationId"",
                            ""Customers"".""FCMServerKey""      as ""FCMServerKey"",
                            ""Customers"".""AppId""             as ""AppId""
            from ""CustomerEvents""
                     inner join ""Customers"" on ""CustomerEvents"".""CustomerId"" = ""Customers"".""CustomerId""
            where  ""Customers"".""AdvertiserId"" = @AdvertiserId and ""Data"" #> @SearchField = @SearchValue"; 

        var res = _applicationDbContext.BySearchFieldCustomerApiModels.FromSql(rawSql,
            new NpgsqlParameter("SearchField", advertiser.SearchField),
            new NpgsqlParameter("SearchValue", searchValue),
            new NpgsqlParameter<int>("AdvertiserId", advertiser.AdvertiserId));

        return res;
    }
}

SearchField有什么想法可以SearchValue正确通过吗?

标签: c#postgresql.net-corenpgsql

解决方案


使用文本参数,而不是使用#>use #>>。前者需要一个jsonb参数,而后者需要一个text参数(参见 PostgreSQL 文档)。

您的代码在 DataGrip 中工作的原因是'{inner_id}'直接嵌入在 SQL 中的无类型文字,因此 PostgreSQL 将其隐式转换为jsonb. 然而,当使用 Npgsql 的参数时,Npgsql 发送一个类型化text参数(Npgsql 的参数(几乎)总是类型化),因此 PostgreSQL 抱怨不匹配。


推荐阅读