简体   繁体   English

使用 Dapper (C#) 调用 PostgreSQL 存储过程

[英]Using Dapper (C#) to call PostgreSQL stored procedure

I'm posting this for two reasons我发布这个有两个原因

  1. I'm new to PostgreSQL and it took a while to piece this information together, so I thought someone else would find this helpful and我是 PostgreSQL 的新手,将这些信息拼凑在一起需要一段时间,所以我认为其他人会觉得这很有帮助并且
  2. to ask if there is another way to call a PostgreSQL stored procedure that doesn't require all of the parameters to be included in the stored procedure name/signature.询问是否有另一种方法来调用不需要所有参数都包含在存储过程名称/签名中的 PostgreSQL 存储过程。

The following uses Dapper and Npgsql to make a call to a PostgreSQL stored procedure that inserts (null id_inout passed in) or updates a record (id_inout has a value).下面使用 Dapper 和 Npgsql 调用 PostgreSQL 存储过程,该存储过程插入(传入的空 id_inout)或更新记录(id_inout 有值)。

I'd like to understand why PostgreSQL requires the entire stored procedure signature when making the call.我想了解为什么 PostgreSQL 在进行调用时需要整个存储过程签名。

    public static int? PO_Save(PurchaseOrder po)
    {

        int? recordId = null;           

        using (var cn = new NpgsqlConnection(AppSettings.ConnectionString))
        {
            if (cn.State != ConnectionState.Open)
                cn.Open();

            var procName = "CALL po_save(@in_ponumber,@in_deliverydate,@in_bldnum," +
                "@in_facname,@in_facnumber,@in_facaddress1,@in_facaddress2,@in_city," +
                "@in_state,@in_zip,@in_theme,@id_inout)";
            var p = new Dapper.DynamicParameters();
            p.Add("@in_ponumber", po.PONumber);
            p.Add("@in_deliverydate", po.DeliveryDate);
            p.Add("@in_bldnum", po.BldNum);
            p.Add("@in_facname", po.FacName);
            p.Add("@in_facnumber", po.FacNumber);
            p.Add("@in_facaddress1", po.FacAddress1);
            p.Add("@in_facaddress2", po.FacAddress2);
            p.Add("@in_city", po.City);
            p.Add("@in_state", po.State);
            p.Add("@in_zip", po.Zip);
            p.Add("@in_theme", po.Theme);
            p.Add("@id_out", po.POID, null, ParameterDirection.InputOutput);
            var res = cn.Execute(procName, p);
            recordId = p.Get<int>("@id_inout");
        }

        return recordId;
    }

You should be able to pass commandType: CommandType.StoredProcedure to Execute , eg:您应该能够将commandType: CommandType.StoredProcedure传递给Execute ,例如:

var res = cn.Execute(
    "po_save",
    new {
        in_ponumber = po.PONumber,
        in_deliverydate = po.DeliveryDate,
        // etc...
    },
    commandType: CommandType.StoredProcedure,
);

Here's the docs with such an example: https://github.com/StackExchange/Dapper/blob/main/Readme.md#stored-procedures这是带有此类示例的文档: https://github.com/StackExchange/Dapper/blob/main/Readme.md#stored-procedures

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

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