TransactionScope只要一个操作失败,它会自动回滚,Complete表示事务完成

实事上,一个错误的理解就是Complete()方法是提交事务的,这是错误的,事实上,它的作用的表示本事务完成,它一般放在try{}的结尾处,不用判断前台操作是否成功,如果不成功,它会自己回滚。

  #region 事务问题
            using (TransactionScope trans = new TransactionScope())
            {
                try
                {
                    InsertUserBase(); //它插入不成功,自己回滚

                    UserInfos userInfo = new UserInfos
                    {
                        UserID = "1",
                        RealName = "zzl",
                    };
                    db.UserInfos.InsertOnSubmit(userInfo);
                    db.SubmitChanges();

                    trans.Complete();
                }
                catch (Exception)
                {

                    // throw;
                }
                finally
                {
                    trans.Dispose();
                }
            }
            #endregion

  static bool InsertUserBase()
        {

            bool flag;
            try
            {
                UserBases userbase = new UserBases
                {
                    UserID = "0005",
                    Name = "zzl",
                    CreateDate = DateTime.Now,
                    UpdateDate = DateTime.Now,

                };
                db.UserBases.InsertOnSubmit(userbase);
                db.SubmitChanges();
                flag = true;
            }
            catch (Exception)
            {

                throw;
            }
            return flag;

        }

InsertUserBase()只要出现异常,程序将自己回滚

posted @ 2011-10-18 09:26  张占岭  阅读(8765)  评论(8编辑  收藏  举报