简体   繁体   English

通过Npgsql调用时,“ Upsert” /合并功能的数据提交失败

[英]Data commit fails for “Upsert” / Merge function when calling through Npgsql

I am using Npgsql 3.0.3 with Postgres 9.4. 我在Postgres 9.4中使用Npgsql 3.0.3。 Here is my code in Postgres: 这是我在Postgres中的代码:

CREATE TABLE temp_test
(
  id serial NOT NULL,
  name text,
  CONSTRAINT temp_test_pk PRIMARY KEY (id)
)

and the "Upsert" / merge function that returns the changed record as refcursor: 和“ Upsert” /合并功能,将更改后的记录作为refcursor返回:

CREATE OR REPLACE FUNCTION test_save(
    v_ref refcursor,
    iv_id integer,
    v_name character varying)
  RETURNS refcursor AS
$BODY$ 
DECLARE
  v_ref alias for $1;
  v_id integer := iv_id;
BEGIN

  UPDATE onepm.temp_test
  SET name   = v_name
  WHERE id         = v_id;
  IF NOT FOUND THEN
  INSERT INTO onepm.temp_test
      (name)
  VALUES
      (v_name)
  RETURNING id INTO v_id;
  END IF;

  OPEN v_ref FOR
  SELECT id 
       , name
  FROM onepm.temp_test
  WHERE id = v_id;

  RETURN v_ref;
END;

$BODY$
  LANGUAGE plpgsql;

In my .net project I have the following function that returns a IDatareader: 在我的.net项目中,我具有以下返回IDatareader的函数:

public static IDataReader ExecuteReader()
        {
            NpgsqlConnection conn = new NpgsqlConnection(connectionString);
            conn.Open();

            NpgsqlTransaction _tran = conn.BeginTransaction();

            NpgsqlCommand cmd = conn.CreateCommand();
            cmd.CommandType = CommandType.Text;
            cmd.CommandText = "SELECT onepm.test_save(@ref, @id, @name)";

            NpgsqlParameter _p = new NpgsqlParameter();
            _p.ParameterName = "@ref";
            _p.NpgsqlDbType = NpgsqlDbType.Refcursor;
            _p.NpgsqlValue = "ref";
            _p.Direction = ParameterDirection.InputOutput;
            cmd.Parameters.Add(_p);

            cmd.Parameters.Add(new NpgsqlParameter("@id", 1));
            cmd.Parameters.Add(new NpgsqlParameter("@name", "test"));

            cmd.ExecuteNonQuery();
            cmd.CommandText = "fetch all in \"ref\"";
            cmd.CommandType = CommandType.Text;

            return cmd.ExecuteReader();
        }

This all works fine, I do receice the inserted or updated record in the reader, except that the data is never committed to the table - no data found in pgAdmin. 这一切都很好,我确实会在阅读器中接收到插入或更新的记录,只是数据永远不会提交到表中(在pgAdmin中找不到数据)。 If I call the same function in pgAdmin everything works fine - records are committed: 如果我在pgAdmin中调用相同的函数,则一切正常-提交记录:

SELECT onepm.test_save('v_ref', 1, 'xxxxxx');

FETCH ALL IN "v_ref";

Thankful for any help! 感谢您的帮助!

Ummm, I think you need to commit the transaction you started...! 嗯,我认为您需要提交您启动的交易...!

Regardless, you may also want to look at PostgreSQL 9.5's new built-in upsert functionality... 无论如何,您可能还想看看PostgreSQL 9.5的新内置upsert功能...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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