Пример #1
0
        public static int GetTransaction()
        {
            DbTransaction trans = DbUtils.GetTransaction("/");

            sTransactions.AddOrUpdate(trans.GetHashCode(), trans, (key, value) =>
            {
                return(trans);
            });
            return(trans.GetHashCode());
        }
Пример #2
0
        public static int GetTransaction(string path,
                                         IsolationLevel level = IsolationLevel.Unspecified)
        {
            DbTransaction trans = DbUtils.GetTransaction(path.ToLower(), level);

            sTransactions.AddOrUpdate(trans.GetHashCode(), trans, (key, value) =>
            {
                return(trans);
            });
            return(trans.GetHashCode());
        }
Пример #3
0
 public void Commit()
 {
     try
     {
         tx.Commit();
         logger.Write(Severity.Debug, "Transaction " + tx.GetHashCode() + " commited");
     }
     catch (Exception ex)
     {
         logger.Write(Severity.Error, ex.Message);
         throw ex;
     }
 }
Пример #4
0
 /// <summary>
 /// This method is called before <see cref="DbTransaction.Dispose()" /> is invoked.
 /// The default implementation of this method filters by <see cref="DbContext" /> set into
 /// <see cref="Context" />, if any, and then logs the event.
 /// </summary>
 /// <param name="transaction">The transaction being disposed.</param>
 /// <param name="interceptionContext">Contextual information associated with the call.</param>
 public virtual void Disposing(DbTransaction transaction, DbTransactionInterceptionContext interceptionContext)
 {
     if (ShouldLog(interceptionContext) && transaction.Connection != null)
     {
         LogInformation("Disposed transaction {0}", transaction.GetHashCode());
     }
 }
Пример #5
0
        private string GetTransactionInformation(DbTransaction value)
        {
            if (value == null)
            {
                return("Transaction is null");
            }

            return($"TransactionHashCode: {value.GetHashCode()}\r\n" +
                   $"TransactionIsolationLevel: {value.IsolationLevel}\r\n" +
                   "Transaction connection details: " + GetConnectionInfo(value.Connection) + "\r\n");
        }
Пример #6
0
        /// <summary>
        /// 对数据库连接开启事务
        /// </summary>
        public virtual void BeginOrUseTransaction()
        {
            if (_dbContexts.Count == 0)
            {
                return;
            }
            if (_transaction?.Connection == null)
            {
                if (_connection.State != ConnectionState.Open)
                {
                    _connection.Open();
                }

                _transaction = _connection.BeginTransaction();
                _logger.LogDebug($"在连接 {_connection.ConnectionString} 上开启新事务,事务标识:{_transaction.GetHashCode()}");
            }

            foreach (DbContextBase context in _dbContexts)
            {
                if (context.Database.CurrentTransaction != null && context.Database.CurrentTransaction.GetDbTransaction() == _transaction)
                {
                    continue;
                }
                if (context.IsRelationalTransaction())
                {
                    context.Database.UseTransaction(_transaction);
                    _logger.LogDebug($"在上下文 {context.GetType()} 上应用现有事务,事务标识:{_transaction.GetHashCode()}");
                }
                else
                {
                    context.Database.BeginTransaction();
                }
            }

            HasCommitted = false;
        }
Пример #7
0
        /// <summary>
        /// 回滚所有事务
        /// </summary>
        public virtual void Rollback()
        {
            foreach (DbConnection connection in _transDict.Keys)
            {
                DbTransaction transaction = _transDict[connection];
                if (transaction.Connection == null)
                {
                    continue;
                }

                transaction.Rollback();
                _logger.LogDebug($"回滚事务,事务标识:{transaction.GetHashCode()}");
            }

            HasCommitted = true;
        }
Пример #8
0
 /// <summary>
 /// This method is called after <see cref="DbTransaction.Commit" /> is invoked.
 /// The default implementation of this method filters by <see cref="DbContext" /> set into
 /// <see cref="Context" />, if any, and then logs the event.
 /// </summary>
 /// <param name="transaction">The transaction that was commited.</param>
 /// <param name="interceptionContext">Contextual information associated with the call.</param>
 public virtual void Committed(DbTransaction transaction, DbTransactionInterceptionContext interceptionContext)
 {
     if (ShouldLog(interceptionContext))
     {
         if (interceptionContext.Exception != null)
         {
             LogError(
                 interceptionContext.Exception,
                 $"Failed to commit transaction with error: {interceptionContext.Exception.Message}");
         }
         else
         {
             LogInformation("Committed transaction {0}", transaction.GetHashCode());
         }
     }
 }
Пример #9
0
        public Transaction(DbConnection conn)
        {
            try
            {
                logger = LoggerFactory.CreateTraceLogger();

                this.conn = conn;
                tx        = conn.BeginTransaction();

                logger.Write(Severity.Debug, "Transaction " + tx.GetHashCode() + " created");
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
Пример #10
0
        /// <summary>
        /// 异步回滚所有事务
        /// </summary>
        /// <returns></returns>
        public virtual async Task RollbackAsync(CancellationToken cancellationToken = default)
        {
            foreach (DbConnection connection in _transDict.Keys)
            {
                DbTransaction transaction = _transDict[connection];
                if (transaction.Connection == null)
                {
                    continue;
                }

                await transaction.RollbackAsync(cancellationToken);

                _logger.LogDebug($"回滚事务,事务标识:{transaction.GetHashCode()}");
            }

            HasCommitted = true;
        }
Пример #11
0
        /// <summary>
        /// 对数据库连接开启事务
        /// </summary>
        /// <param name="cancellationToken">异步取消标记</param>
        /// <returns></returns>
        public virtual async Task BeginOrUseTransactionAsync(CancellationToken cancellationToken = default(CancellationToken))
        {
            if (_dbContexts.Count == 0)
            {
                return;
            }
            if (_transaction?.Connection == null)
            {
                if (_connection.State != ConnectionState.Open)
                {
                    await _connection.OpenAsync(cancellationToken);
                }
#if NETSTANDARD2_0
                _transaction = _connection.BeginTransaction();
#else
                _transaction = await _connection.BeginTransactionAsync(cancellationToken);
#endif
                _logger.LogDebug($"在连接 {_connection.ConnectionString} 上开启新事务,事务标识:{_transaction.GetHashCode()}");
            }

            foreach (DbContextBase context in _dbContexts)
            {
                if (context.Database.CurrentTransaction != null && context.Database.CurrentTransaction.GetDbTransaction() == _transaction)
                {
                    continue;
                }
                if (context.IsRelationalTransaction())
                {
                    await context.Database.UseTransactionAsync(_transaction, cancellationToken);

                    _logger.LogDebug($"在上下文 {context.GetType()} 上应用现有事务");
                }
                else
                {
                    await context.Database.BeginTransactionAsync(cancellationToken);
                }
            }

            HasCommitted = false;
        }
Пример #12
0
        /// <summary>
        /// 提交当前上下文的事务更改
        /// </summary>
        public virtual void Commit()
        {
            if (HasCommitted || _contextDict.IsEmpty || _transDict.IsEmpty)
            {
                return;
            }

            string token;

            if (_transactionStack.Count > 1)
            {
                token = _transactionStack.Pop();
                _logger.LogDebug($"跳过事务提交,标识:{token},当前剩余标识数:{_transactionStack.Count}");
                return;
            }

            if (!IsEnabledTransaction)
            {
                throw new OsharpException("执行 IUnitOfWork.Commit() 之前,需要在事务开始时调用 IUnitOfWork.EnableTransaction()");
            }

            token = _transactionStack.Pop();
            foreach (KeyValuePair <DbConnection, DbTransaction> pair in _transDict)
            {
                DbConnection  connection  = pair.Key;
                DbTransaction transaction = pair.Value;
                transaction.Commit();
                _logger.LogDebug($"提交事务,标识:{token},事务标识:{transaction.GetHashCode()}");
                if (_contextDict.TryGetValue(connection, out List <DbContextBase> contexts))
                {
                    foreach (var context in contexts)
                    {
                        context.Database.UseTransaction(null);
                        _logger.LogDebug($"上下文 {context.GetType()}[标识:[{context.GetHashCode()}] 释放事务,事务标识:{transaction.GetHashCode()}");
                    }
                }
            }

            HasCommitted = true;
        }
Пример #13
0
        /// <summary>
        /// 创建事务
        /// </summary>
        /// <returns>事务号</returns>
        public static string CreateTransaction <T>() where T : BaseModel, new()
        {
            DbConnection  connection = GetConnection <T>();
            DbTransaction tran       = null;
            string        key        = "";

            try
            {
                connection.Open();
                tran = connection.BeginTransaction();
                key  = tran.GetHashCode().ToString();
                TranRecord record = new TranRecord()
                {
                    LastCall = DateTime.Now, Tran = tran
                };
                tranPool.Add(key, record);
            }
            catch (Exception ex)
            {
            }
            return(key);
        }