使用SqlTransaction连接已关闭错误

时间:2013-08-12 14:59:32

标签: c# asp.net sql-server transactions

我有一个测试SQL Server表,其中包含

等数据
  ItemId    Description ItemCost
    1           first item  100
    2           second item 200
    3           third item  300

以及将项目添加到Items

的存储过程
create proc spInsertItem
 @itemId int
,@itemDescription varchar(50)
,@itemCost decimal
as
begin
    if(@itemCost < 0)
        begin
            raiserror('cost cannot be less than 0',16,1)
        end
    else
        begin
            begin try
                begin tran
                    insert into Items(itemid, [description],itemCost)
                    values (@itemid, @itemdescription,@itemCost)
                commit tran
            end try
        begin catch
            rollback tran
                select   ERROR_LINE()as errorLine
                        ,ERROR_MESSAGE() as errorMessage
                        ,ERROR_STATE() as errorState
                        ,ERROR_PROCEDURE() as errorProcedure
                        ,ERROR_NUMBER() as errorNumber
        end catch
    end
end 

当我在SSMS中执行该过程时,它会正确报告负成本错误。当我使用以下代码时:

protected void btnSubmit_Click(object sender, EventArgs e)
        {
            string cs = ConfigurationManager.ConnectionStrings["dbcsI3"].ConnectionString;
            using (var con = new SqlConnection(cs))
            {
                SqlTransaction tran = con.BeginTransaction();
                try
                {
                    using (var cmd = new SqlCommand("spInsertItem", con))
                    {

                        con.Open();
                        cmd.CommandType = CommandType.StoredProcedure;
                        cmd.Parameters.AddWithValue("@itemId", Convert.ToInt32(txtItemId.Text));
                        cmd.Parameters.AddWithValue("@itemdescription", txtItemDescription.Text);
                        cmd.Parameters.AddWithValue("@itemCost", Convert.ToInt32(txtItemCost.Text));
                        cmd.ExecuteNonQuery();
                        tran.Commit();
                    }
                }
                catch (Exception ex)
                {
                    lblStatus.Text = ex.Message; //the intent is to print the error message to the user 
                    tran.Rollback();
                }
            }
        }

当我使用这段代码时,我得到一个连接已关闭的异常,但后来我跳到SSMS并发现它工作正常。在我搬家之前把所有东西都用到工作之前我想知道为什么我得到连接关闭的错误。每当我在该表中输入可行数据时,该过程也会起作用。

1 个答案:

答案 0 :(得分:5)

尝试在BeginTransaction

之前打开连接
using (var con = new SqlConnection(cs))
{
   con.Open();
   SqlTransaction tran = con.BeginTransaction(); 
   // rest of the code