TransactionScope事务操作

Posted shy1766it

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了TransactionScope事务操作相关的知识,希望对你有一定的参考价值。

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

 

以上是关于TransactionScope事务操作的主要内容,如果未能解决你的问题,请参考以下文章

transactionscope报“此操作对该事务的状态无效”问题

TransactionScope事务

TransactionScope 如何回滚事务?

C#分布式事务解决方案-TransactionScope

TransactionScope:避免分布式事务

TransactionScope 事务 = new TransactionScope() VS TransactionScope s = context.Connection.BeginTransac