11

I'm trying to insert JSON data into a JSONB PostgreSQL column using Dapper.Net.

The NPGSQL Documentation for JSONB gives specific instructions to use the NpgsqlDbType.Jsonb datatype.

With Dapper, I'm trying to add this as a custom parameter without success.

using (var conn = myconnection)
{
    var sql = "INSERT INTO mytable (jsonbody) VALUES (@jb);";
    dp =  new DynamicParameters();
    dp.Add("jb", stringOfJsonData, (DbType)NpgsqlDbType.Jsonb);
    await conn.ExecuteAsync(sql,dp);                    
}                

The error I'm receiving is System.NotSupportedException : The parameter type DbType.36 isn't supported by PostgreSQL or Npgsql

Any suggestions on how to use these two libraries together for JSONB?

Thanks.

2 Answers 2

14

It appears that changing the SQL statement to the following fixed it.

var sql = "INSERT INTO mytable (jsonbody) VALUES (CAST(@jb AS json));";

Also, there's no need to specify the type in the parameter mapping.

dp.Add("jb", stringOfJsonData)
Sign up to request clarification or add additional context in comments.

Comments

2

NpgsqlDbType and DbType are two different enums, you can't simply cast one into the other...

You'll have to make for set the NpgsqlDbType property on the NpgsqlParameters it creates and send. IIRC there's a way to specify custom parameters.

1 Comment

You can use this overload of AddWithValue, for example. Or instantiate an NpgsqlParameter yourself, set its NpgsqlDbType property and add it to the command's parameter collection.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.