[英]How to convert a json string into jsonb type using postgres in c#
我正在使用 .NET 核心 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 的新手,在我的要求中我不能使用实体框架。 我需要做什么才能将 Json 字符串转换为 jsonb 类型的 postgres?
Postgres 通常避免隐式转换:从它的角度来看,您试图在 jsonb 列中插入一个字符串。
我认为您需要在查询中进行显式转换。 更改以下代码行应该足够好:
var valuesTableSql = string.Join(",", Enumerable.Range(0, result.Count).Select(i => $"(@p1{i}, @p2{i})::jsonb"));
正如@GMB 所写,PostgreSQL 不会将字符串隐式转换为 jsonb。 但是,除了在 SQL 中应用强制转换,您还可以指示 Npgsql 发送类型为jsonb
的参数:
cmd.Parameters.AddWithValue("p1", NpgsqlDbType.Jsonb, "{....}");
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.