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

时间:2019-10-09 13:24:02

标签: c# postgresql .net-core npgsql

我有以下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#>文本

我将向您展示我的代码:

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;
    }
}

有什么想法可以正确地通过SearchFieldSearchValue吗?

2 个答案:

答案 0 :(得分:2)

要使用文本参数,请使用#>,而不要使用#>>。前者期望使用jsonb参数,而后者期望使用text参数(see the PostgreSQL docs)。

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

答案 1 :(得分:1)

添加一个显式类型转换,以便PostgreSQL知道字符串文字将被解释为数组:

var rawSql = @"
            ...
            where  ""Data"" #>> CAST(@SearchField AS text[]) = @SearchValue";