如何在C#中使用postgres将json字符串转换为jsonb类型

问题描述 投票:0回答:2

我正在使用.NET core 3.1

我的postgres数据库中有一个2列的表

+---------+--------+
| id      | bigint |
+---------+--------+
| content | jsonb  |
+---------+--------+

而且我正在尝试在列上放置如下内容的json字符串:

"{\"Id\":247764684382208,\"Created\":\"2020-06-08T00:00:00Z\",\"Content\":\"Ad in consequat duis qui sit eu nulla magna consectetur id anim\",\"ReceivedTimestamp\":\"0001-01-01T00:00:00\",\"MessageEventId\":0}"

在我的代码中,我执行以下操作:

[result变量是具有(key = long,value = string)字典的IColletion,其字典值与我上面发布的字典相同

string connString = "Host=localhost;Port=5432;Username=postgres;Password=postgres;Database=testdb";

NpgsqlConnection conn = new NpgsqlConnection(connString);

conn.Open();

var valuesTableSql = string.Join(",", Enumerable.Range(0, result.Count).Select(i => $"(@p1{i}, @p2{i})"));

using (var cmd = new NpgsqlCommand($"INSERT INTO \"table\" (\"id\", \"content\") VALUES {valuesTableSql};", conn)) 
{
 for (int i = 0; i < result.Messages.Count; ++i)
  {
   cmd.Parameters.AddWithValue($"p1{i}", result.ElementAt(i).Key);
   cmd.Parameters.AddWithValue($"p2{i}", result.Messages.ElementAt(i).Value);
 }
}

当我运行代码时,我会得到这样的异常:

Unhandled exception. Npgsql.PostgresException (0x80004005): 42804: column "content" is of type jsonb but expression is of type text

我是Postgres的新手,根据我的要求,我不能使用Entity Framework。我需要在那里将Json字符串转换为PostgreSQLb的jsonb类型吗?

c# postgresql .net-core sql-insert npgsql
2个回答
2
投票

Postgres通常避免隐式转换:从其角度来看,您正在尝试在jsonb列中插入字符串。

我认为您需要在查询中进行显式转换。更改以下代码行就足够了:

var valuesTableSql = string.Join(",", Enumerable.Range(0, result.Count).Select(i => $"(@p1{i}, @p2{i})::jsonb"));

0
投票

如@GMB所写,PostgreSQL不会将字符串隐式转换为jsonb。但是,除了在SQL内部应用强制转换外,您还可以指示Npgsql发送类型为jsonb的参数:

cmd.Parameters.AddWithValue("p1", NpgsqlDbType.Jsonb, "{....}");
© www.soinside.com 2019 - 2024. All rights reserved.