Exemplo n.º 1
0
        /// <summary>回滚事务</summary>
        /// <param name="ignoreException">是否忽略异常</param>
        /// <returns>剩下的事务计数</returns>
        public Int32 Rollback(Boolean ignoreException = true)
        {
            // 这里要小心,在多层事务中,如果内层回滚,而最外层提交,则内层的回滚会变成提交
            TransactionCount--;
            if (TransactionCount > 0)
            {
                return(TransactionCount);
            }

            var tr = Trans;

            if (tr == null)
            {
                throw new XDbSessionException(this, "当前并未开始事务,请用BeginTransaction方法开始新事务!");
            }
            Trans = null;

            // 输出事务日志
            if (Setting.Current.TransactionDebug)
            {
                XTrace.DebugStack();
            }
            try
            {
                if (tr.Connection != null)
                {
                    tr.Rollback();

                    foreach (var item in _EntitySession)
                    {
                        var dirtiedSession = item.Value;
                        if (dirtiedSession.ExecuteCount > 0)
                        {
                            dirtiedSession.Session.RaiseRoolbackDataChange(dirtiedSession.UpdateCount, dirtiedSession.DirectExecuteSQLCount);
                        }
                    }
                }
            }
            catch (DbException ex)
            {
                if (!ignoreException)
                {
                    throw OnException(ex);
                }
            }
            finally
            {
                tr = null;
                _EntitySession.Clear();
                if (IsAutoClose)
                {
                    Close();
                }
            }

            return(TransactionCount);
        }