简体   繁体   中英

Geting result from json or jsonb result from stored procedure with Dapper and Postgresql in C#

I have this stored procedure in database :

CREATE OR REPLACE PROCEDURE sources_v2.sp_test(INOUT out_param_text text DEFAULT ''::text, INOUT out_param_json json DEFAULT '{}'::json, INOUT out_param_jsonb jsonb DEFAULT '{}'::jsonb)
 LANGUAGE plpgsql
AS $procedure$
DECLARE
    
BEGIN
    out_param_text := 'Hello World !';
    SELECT to_json('{"Hello": "World"}'::text) INTO out_param_json;
    SELECT to_jsonb('{"Hello": "World"}'::text) INTO out_param_jsonb;
    
    RETURN;
END; $procedure$
;

I called it like this:

DynamicParameters parameters = new DynamicParameters();
parameters.Add("out_param_text","", DbType.String, ParameterDirection.InputOutput);
parameters.Add("out_param_json", new JsonParameter("{}"), null, ParameterDirection.InputOutput);
parameters.Add("out_param_jsonb", new JsonBParameter("{}"), null, ParameterDirection.InputOutput);

result = _DbRepositoryCommon.execStoredProcedure<DataListReturnModelRepository<T>>("sp_test(:out_param_text, :out_param_json, :out_param_jsonb)", parameters);

and in _DbRepositoryCommon :

public T execStoredProcedure<T>(string spxName, DynamicParameters dyParams)
{
    T result = default(T);

    using (IDbConnection connection = GetConnection)
    {
        if (connection.State == ConnectionState.Closed)
        {
            connection.Open();

            try
            {
                connection.Query($"call sources_v2.{spxName}", dyParams);
            }
            catch (Exception ex)
            {
                throw;
            }

            var toto = dyParams.Get<string>("@out_param_text");
            result = returnObjectFromDynamicParameter<T>(dyParams, "returndata");

            connection.Close();
        }
    }

    return result;
}

As you can see, I have no problem to get out_param_text as string, the problem is if I do the same process on out_param_json or out_param_json_b their value are "{}"

So what am I doing wrong?

the solution is to pass null to jon and jsonb param as value like this:

parameters.Add("out_param_json", null, null, ParameterDirection.InputOutput);

parameters.Add("out_param_jsonb", null, null, ParameterDirection.InputOutput);

And to get the return data like this :

var toto = dyParams.Get<dynamic>("@out_param_text");
var toto = dyParams.Get<dynamic>("@out_param_jsonb");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM