0

我有一个测试 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 并发现它工作正常。在我四处移动以使所有东西都正常工作之前,我想知道为什么我会收到连接已关闭的错误。每当我在该表中输入可行的数据时,该过程也有效。

4

1 回答 1

7

尝试打开连接之前BeginTransaction

using (var con = new SqlConnection(cs))
{
   con.Open();
   SqlTransaction tran = con.BeginTransaction(); 
   // rest of the code 
于 2013-08-12T15:04:46.850 回答