首页 > 解决方案 > 使用 EF Core 中的 Database.ExecuteSqlCommand 从 MySql 存储过程中读取输出参数

问题描述

我在 MySQL 中有以下包含输出参数的存储过程。存储过程在数据库服务器上执行时有效。

CALL `db`.`usp_AgentTransferPortalsDisplayed`(@val);

select @val

我正在尝试使用以下内容使用 Entity Framework Core 调用此存储过程。

var count = ctx.Database.ExecuteSqlCommand("CALL db.usp_AgentTransferPortalsDisplayed(@output);",
                new MySqlParameter("@output", MySqlDbType.Int32));

我收到以下错误:

MySql.Data.MySqlClient.MySqlException 已被抛出:“例程 db.usp_AgentTransferPortalsDisplayed 的 OUT 或 INOUT 参数 1 不是 BEFORE 触发器中的变量或新伪变量”

我不确定我是否使用了正确的语法,因为这是一个输出参数。

我也尝试过这种方式:

        var outParam = new MySqlParameter();
        outParam.Direction = ParameterDirection.Output;
        outParam.DbType = DbType.Int32;

        var count = ctx.Database.ExecuteSqlCommand("CALL db.usp_AgentTransferPortalsDisplayed(@outParam);", outParam);

MySql.Data.MySqlClient.MySqlException:“命令执行过程中遇到致命错误。” ---> System.Exception {MySql.Data.MySqlClient.MySqlException}:“必须定义参数'@outParam'。” 在

更新

基于马特建议的链接;我能够使用以下语法来做到这一点:

    using (MySqlConnection lconn = new MySqlConnection(conn))
    {
        lconn.Open();
        using (MySqlCommand cmd = new MySqlCommand())
        {
            cmd.Connection = lconn;
            cmd.CommandText = "db.usp_AgentTransferPortalsDisplayed"; // The name of the Stored Proc
            cmd.CommandType = CommandType.StoredProcedure; // It is a Stored Proc

            cmd.Parameters.AddWithValue("@result", MySqlDbType.Int32);
            cmd.Parameters["@result"].Direction = ParameterDirection.Output; // from System.Data
            cmd.ExecuteNonQuery(); // let it rip
            Object obj = cmd.Parameters["@result"].Value;
            var lParam = (Int32)obj;    // more useful datatype
        }
    }

标签: c#mysqlentity-framework

解决方案


推荐阅读