日期:2014-05-17  浏览次数:20435 次

TransactionScope没有自动回滚?
按书上的说法,使用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','设计部','北京','a@126.com')", conn);
                            cmd.ExecuteNonQuery();
                            cmd = new SqlCommand("insert into employee values(8,'B','程序部','上海','b@sohu.com')", conn);
                            cmd.ExecuteNonQuery();
                            this.Label1.Text = "OK!";
                        }
                        catch(Exception ex)
                        {
                            this.Label1.Text = ex.Message;
            &nb