按书上的说法,使用TransactionScope创建事务代码块(在数据库表中插入两条记录),运行后显示
违反了 PRIMARY KEY 约束 'PK_Employee'。不能在对象 'dbo.Employee' 中插入重复键。 语句已终止。
这个是预期的,但查数据表后,发现第一条insert语句成功插入了,没有回滚?代码如下,烦劳指导一下:
protected void Page_Load(object sender, EventArgs e)
        {
            if (!Page.IsPostBack)
            {
                using (TransactionScope trans = new TransactionScope())
                {
                    using (SqlConnection conn = new SqlConnection(WebConfigurationManager.ConnectionStrings["DotNetDb"].ConnectionString))
                    {
                        try
                        {
                            conn.Open();
                            SqlCommand cmd;
                            cmd = new SqlCommand("insert into employee values(8,'A','设计部','北京','[email protected]')", conn);
                            cmd.ExecuteNonQuery();
                            cmd = new SqlCommand("insert into employee values(8,'B','程序部','上海','[email protected]')", conn);
                            cmd.ExecuteNonQuery();
                            this.Label1.Text = "OK!";
                        }
                        catch(Exception ex)
                        {
                            this.Label1.Text = ex.Message;
                        }
                    }
                    trans.Complete();
                }
            }
        }TransactionScope回滚失败insert

解决方案 »

  1.   

    你的代码没有事务回滚操作。
    在catch里面加上
    trans.Rollback()
      

  2.   

    问题的症结在这里trans.Complete();Complete会交将事务提交(commit),所以出错前的SQL当前就执行了,将你的代码改成下面这样就行了protected void Page_Load(object sender, EventArgs e)
    {
        if (!Page.IsPostBack)
        {
            try
            {
                using (TransactionScope trans = new TransactionScope())
                {
                    using (SqlConnection conn = new SqlConnection(WebConfigurationManager.ConnectionStrings["DotNetDb"].ConnectionString))
                    {
                        conn.Open();
                        SqlCommand cmd;
                        cmd = new SqlCommand("insert into employee values(8,'A','设计部','北京','[email protected]')", conn);
                        cmd.ExecuteNonQuery();
                        cmd = new SqlCommand("insert into employee values(8,'B','程序部','上海','[email protected]')", conn);
                        cmd.ExecuteNonQuery();
                          this.Label1.Text = "OK!";
                    }
                    
                    trans.Complete();
                }
            }
            catch(Exception ex)
            {
                this.Label1.Text = ex.Message;
            }
        }
    }
      

  3.   

    谢谢回复,TransactionScope没有Rollback方法
      

  4.   

    在dispose之前不调用complete就会回滚了...
      

  5.   

    谢谢,需要将Complete()包含在try块中