升级 .NET Core 时 Postgres 功能不起作用

abh*_*rma 0 postgresql npgsql

当我们将 .net core 和其他软件包升级到最新版本时,Postgres 功能无法正常工作。早些时候,相同的代码运行得很好。

我们使用函数而不是存储过程。

DbTransaction transaction = connection.BeginTransaction(IsolationLevel.ReadCommitted);

try
{
        using (DbCommand command = connection.CreateCommand())
        {
            command.Transaction = transaction;
            command.CommandType = CommandType.StoredProcedure;
            command.CommandText = Constants.StoredProcedure.SPNAME;
            command.Parameters.Add(new NpgsqlParameter("Param1", NpgsqlTypes.NpgsqlDbType.Integer)
            { Value = val1 });
            command.Parameters.Add(new NpgsqlParameter("Param2", NpgsqlTypes.NpgsqlDbType.Varchar)
            { Value = val2 });
            command.Parameters.Add(new NpgsqlParameter("Param3", NpgsqlTypes.NpgsqlDbType.Varchar)
            { Value = val3 });
            var res = command.ExecuteScalar();
            transaction.Commit();
}}
Run Code Online (Sandbox Code Playgroud)

错误 - Npgsql.PostgresException:'42809:public.NotableEventUserModeratorJoinOrder(Param1 => 整数,Param2 => 字符变化,Param3 => 字符变化)不是过程

我们注释了行command.CommandType = CommandType.StoredProcedure;,然后收到错误 - PostgreSQL,Npgsql 返回 42601:语法错误

JGH*_*JGH 6

这是npgsql 7 中记录的重大更改。

关于存储过程/函数的文档还说:

警告

从 Npgsql 7.0 开始,CommandType.StoredProcedure 现在调用存储过程,而不是像以前那样运行。有关更多信息以及如何选择退出此更改,请参阅发行说明。

这两个选项是

  1. 禁用新功能

NpgsqlCommand.CommandType设置为 时CommandType.StoredProcedure,Npgsql 现在会生成用于调用 PostgreSQL 存储过程的 SQL,而不是像以前一样生成函数。要选择退出此重大更改并继续像以前一样调用函数,请启用 Npgsql.EnableStoredProcedureCompatModeAppContext 开关,如下所示:

AppContext.SetSwitch("Npgsql.EnableStoredProcedureCompatMode", true);

或者

  1. 用常规函数调用你的函数select

using var cmd = new NpgsqlCommand("SELECT my_func(1, 2)", conn);