从 Web API 连接到 SQL 服务器时出现问题

Issue connecting to the SQL server from Web API

我有下面的控制器获取帐户作为输入参数,它连接到 Sql 服务器并且必须调用存储过程传递 account.The 存储过程插入新记录如果帐户不存在并在已经存在时更新它

        string strcon = ConfigurationManager.ConnectionStrings["DBConnection"].ConnectionString;
       SqlConnection DbConnection = new SqlConnection(strcon);
       DbConnection.Open();
       SqlCommand command = new SqlCommand("[dbo].[usp_InserUpadte]", DbConnection);
       command.CommandType = CommandType.StoredProcedure;

       //create type table
       DataTable table = new DataTable();
       table.Columns.Add("AccountID", typeof(string));
       table.Rows.Add(Account);

       SqlParameter parameter = command.Parameters.AddWithValue("@Account_TT", table);
       parameter.SqlDbType = SqlDbType.Structured;
       parameter.TypeName = "Account_TT";

下面是web.config

中的ConnectionString
<connectionStrings>
 <add name="DBConnection"
providerName="System.Data.SqlClient"
connectionString="Data Source=ServerName;Initial Catalog=DatabaseName;Integrated Security=True;MultipleActiveResultSets=True" />
</connectionStrings>

存储过程就像

ALTER PROCEDURE [dbo].[usp_InserUpadte] 
@account_TT AS account_TT READONLY

AS
BEGIN
SET NOCOUNT ON;

BEGIN TRANSACTION;

 MERGE dbo.[Account] prj
 USING @account_TT tt
 ON prj.AccountID = tt.AccountID
 WHEN MATCHED THEN UPDATE SET prj.CounterSeq = prj.CounterSeq+1
 WHEN NOT MATCHED THEN INSERT (AccountID,CounterSeq)
 VALUES (tt.AccountID, 1);

 COMMIT TRANSACTION;

 END;

其中 table 类型是使用

创建的
CREATE TYPE account_TT AS TABLE
(
 AccountID     nvarchar(50),
 )
 GO

当我尝试调用 API 时,它不会抛出任何异常,但 creates/update 也不会抛出存储过程的任何记录。我试图调试添加断点。我看到

DbConnection.Open();

看起来连接没有打开。我可以通过 SQL Management Studio 从我正在使用的同一台服务器连接到 SQL 服务器。谁能告诉我可能是什么问题。

您可能已经打开 connection.Correct 打开连接的方式

string strcon = ConfigurationManager.ConnectionStrings["DBConnection"].ConnectionString;

using(SqlConnection dbConnection = new SqlConnection(strcon))
    {
      if (dbConnection.State==ConnectionState.Closed)
      {                      
          con.Open();   
      }
    }

您没有正确连接到数据库。试试这个:

        using (var connection = new SqlConnection(ConnectionString))
        using (var command = new SqlCommand(commandText, connection) { CommandTimeout = 160, CommandType = commandType })
        using (var dataAdaptor = new SqlDataAdapter(command))
        {
            command.Parameters.AddRange(parameters);

            connection.Open();
            dataAdaptor.Fill(dS);
        }