2017-03-16 62 views
0

我们在数据库中创建了一个存储过程。它工作得很好,但我无法弄清楚如何在我的代码中调用它。出于某种原因,我不断收到回在C#中存储过程(ASP.NET CORE)

过程或函数“GetNextApplicationNumber”需要参数“@ApplicationId”,但未提供。

我的代码:

string connectionString = "THE_CONNECTION_STRING"; 
using (IDbConnection connection = new SqlConnection(connectionString)) 
using (IDbCommand command = connection.CreateCommand()) 
{ 
    command.CommandType = CommandType.StoredProcedure; 

    IDbDataParameter parameter = command.CreateParameter(); 
    parameter.ParameterName = "@ApplicationId"; 
    parameter.Value = applicationId; 
    parameter.DbType = DbType.String; 

    command.Parameters.Add(parameter); 

    command.CommandText = "[dbo].[GetNextApplicationNumber]"; 

    connection.Open(); 

    using (IDataReader reader = command.ExecuteReader()) 
    { 
      string applicationNumber = string.Empty; 

      if (reader.Read()) 
      { 
       applicationNumber = reader.GetValue(0).ToString(); 
      } 

      return applicationNumber; 
    } 
} 

我已经尝试了不少不同的方式(其中大部分似乎已经过时,不再可用)。

+0

您可以尝试使用SQL Server Profiler来analize的SQL发送到您的SQL Server。尽量不要设置参数的DbType属性。 – musium

回答

2

当您设置CommandText属性时,它将清除参数集合。

0

看来你似乎在使用旧的方式。

试试这个队友:

public string GetNextApplicationNumber(int applicationId) 
     { 
      DataTable dt = new DataTable(); 
      try 
      { 
       using (SqlConnection conn = new SqlConnection(connString)) 
       { 
        conn.Open(); 

        using (SqlDataAdapter da = new SqlDataAdapter("GetNextApplicationNumber", conn)) 
        { 

         da.SelectCommand.Parameters.AddWithValue("@ApplicationId", applicationId); 
         da.SelectCommand.CommandType = CommandType.StoredProcedure; 
         da.Fill(dt); 

         string applicationNumber = string.Empty; 

         applicationNumber = dt.Rows[0]["Column_Name"].ToString(); 

         return applicationNumber; 
        } 
       } 
      } 
      catch 
      { 
       throw; 
      } 
     } 
+0

你应该看看[我们可以停止使用AddWithValue()了吗?](http://blogs.msmvps.com/jcoehoorn/blog/2014/05/12/can-we-stop-using-addwithvalue-already/)并停止使用'.AddWithValue()' - 它可能会导致意想不到的和令人惊讶的结果... –

+0

我使用.net核心,它似乎并没有SqlDataAdapter类与核心兼容:( –

0

考虑使用此一:

public static SqlCommand WithParameter(this SqlCommand sqlCommand, SqlParameter parameter) 
    { 
     sqlCommand.Parameters.Add(parameter); 
     return sqlCommand; 
    } 

然后

SqlCommand command = new SqlCommand("[dbo].[GetNextApplicationNumber]",sqlConnection) 
        .WithParameter(new SqlParameter("@ApplicationId", SqlDbType.BigInt) {Value = 1}); 

using (SqlDataReader reader = command.ExecuteReader()) 
{...}