简体   繁体   English

C#ADO.NET - 无法找到存储过程

[英]C# ADO.NET - Could Not Find Stored Procedure

I am trying to execute a stored procedure through C#, ADO.NET and below is the code I am trying to execute: 我试图通过C#,ADO.NET执行存储过程,下面是我试图执行的代码:

using (SqlConnection conn = new SqlConnection(".;Initial Catalog=MyDB;User ID=sa;Password=***"))
            {
                try
                {
                    string cmdText = "dbo.sp_Create_FlaggedItemEntry @URI, @ID";
                    SqlCommand cmd = new SqlCommand();
                    cmd.Connection = conn;
                    conn.Open();
                    cmd.CommandText = cmdText;
                    cmd.CommandType = CommandType.StoredProcedure;
                    cmd.Parameters.AddWithValue("@URI", value1);
                    cmd.Parameters.AddWithValue("@ID", value2);

                    cmd.ExecuteNonQuery();
                }
                catch (Exception ex)
                {
                    throw ex;
                }
                finally
                {
                    if (conn != null)
                    {
                        conn.Close();
                    }
                }
            }

Now when I try to debug it, I got an error at the line - cmd.ExecuteNonQuery(); 现在,当我尝试调试它时,我遇到了一个错误 - cmd.ExecuteNonQuery(); - "Could Not Find Stored Procedure dbo.sp_Create_FlaggedItemEntry" - “找不到存储过程dbo.sp_Create_FlaggedItemEntry”

I verified that the Connection String is all correct and Stored Procedure exists. 我验证了连接字符串是正确的并且存储过程存在。 Further, If I change the line - cmd.CommandType = CommandType.StoredProcedure; 此外,如果我更改行 - cmd.CommandType = CommandType.StoredProcedure; to cmd.CommandType = CommandType.Text; to cmd.CommandType = CommandType.Text; it get executed successfully and as expected. 它成功执行并按预期执行。

Can someone suggest what I am missing and doing wrong here - Please pardon me if it is something very basic as it is quite long since I last worked with ADO.NET 有人可以在这里建议我错过了什么并做错了 - 请原谅我,如果它是非常基本的东西,因为我上次使用ADO.NET已经很久了

CommandType.StoredProcedure means that the CommandText should only contain the name of the stored procedure. CommandType.StoredProcedure意味着CommandText应仅包含存储过程的名称。

Remove the parameter names from the string. 从字符串中删除参数名称。

Take the parameters out of the command text. 从命令文本中取出参数。 Also, you don't need to specify dbo. 此外,您不需要指定dbo。

The reason it's working with CommandType.Text is because it's a legitimate SQL command like that - if you were to open up SSMS and type that in it'd work as long as you also create the variables @URI and @ID 它使用CommandType.Text的原因是因为它是一个合法的SQL命令 - 如果你打开SSMS并输入它就可以工作,只要你还创建变量@URI和@ID

Documentation here 文档在这里

You should mention Data Source / Server in connectionString. 您应该在connectionString中提到数据源/服务器。 Also for CommandText @Slaks is correct. 同样对于CommandText @Slaks也是正确的。

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

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