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()只要出现异常,程序将自己回滚

转载于:https://www.cnblogs.com/lori/archive/2011/10/18/2216086.html

你可能感兴趣的:(TransactionScope只要一个操作失败,它会自动回滚,Complete表示事务完成)