Exemple #1
0
        /// <summary>
        /// 提交事务
        /// </summary>
        /// <returns></returns>
        public virtual async Task CommitAsync()
        {
            if (_DbConnection == null || !_IsCommit)
            {
                return;
            }

            try
            {
                await _DbTransaction.CommitAsync();
            }
            catch (Exception ex)
            {
                if (_DbTransaction?.Connection != null)
                {
                    await _DbTransaction.RollbackAsync();
                }
                throw ex;
            }
            finally
            {
                if (_Db.Database.CurrentTransaction != null)
                {
                    await _Db.Database.CurrentTransaction.DisposeAsync();
                }
                _IsCommit = false;
            }
        }
        public async Task <int> ChangeAnimalAsync()
        {
            using var con = new SqlConnection("Data Source=db-mssql;Initial Catalog=s18378;Integrated Security=True");
            using var com = new SqlCommand("select * from animal", con);

            await con.OpenAsync();

            DbTransaction tran = await con.BeginTransactionAsync();

            com.Transaction = (SqlTransaction)tran;

            try
            {
                var list = new List <Animal>();
                using (var dr = await com.ExecuteReaderAsync())
                {
                    while (await dr.ReadAsync())
                    {
                        list.Add(new Animal
                        {
                            Name        = dr["Name"].ToString(),
                            Description = dr["Description"].ToString()
                        });
                    }
                }

                com.Parameters.Clear();
                com.CommandText = "Update Animal Set Name= Name+ 'a' Where Name= @Name";
                com.Parameters.AddWithValue("@Name", list[0].Name);
                await com.ExecuteNonQueryAsync();

                throw new Exception("Error");

                com.Parameters.Clear();
                com.Parameters.AddWithValue("@Name", list[1].Name);
                await com.ExecuteNonQueryAsync();

                await tran.CommitAsync();
            }
            catch (SqlException exc)
            {
                await tran.RollbackAsync();
            }
            catch (Exception exc)
            {
                await tran.RollbackAsync();
            }
            return(1);
        }
Exemple #3
0
        /// <summary>
        /// 异步回滚
        /// </summary>
        /// <returns></returns>
        public async Task RollbackAsync()
        {
            if (!Enabled)
            {
                return;
            }

            if (_transaction?.Connection != null)
            {
                await _transaction.RollbackAsync();
            }

            if (_dbContext.IsRelationalTransaction())
            {
                if (_dbContext.Database.CurrentTransaction != null)
                {
                    await _dbContext.Database.CurrentTransaction.DisposeAsync();
                }
            }
            else
            {
                _dbContext.Database.RollbackTransaction();
            }

            HasCommitted = true;
        }
Exemple #4
0
        /// <summary>
        /// 异步回滚所有事务
        /// </summary>
        /// <returns></returns>
        public async Task RollbackAsync()
        {
            if (_transaction?.Connection != null)
            {
                await _transaction.RollbackAsync();

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

            foreach (var context in _dbContexts)
            {
                if (context.IsRelationalTransaction())
                {
                    CleanChanges(context);
                    if (context.Database.CurrentTransaction != null)
                    {
                        context.Database.CurrentTransaction.Dispose();
                    }
                    continue;
                }
                context.Database.RollbackTransaction();
            }

            HasCommitted = true;
        }
Exemple #5
0
 private async Task WritingAction(CancellationToken forceStopToken)
 {
     using (ConnectionWrapper connectionWrapper = await manager.GetConnectionAsync(forceStopToken))
     {
         DbCommand command = writerCore.CreateMainCommand(connectionWrapper.Connection);
         while (!forceStopToken.IsCancellationRequested && !DataQueue.IsEmpty)
         {
             using (DbTransaction transaction = await connectionWrapper.Connection.BeginTransactionAsync(forceStopToken))
             {
                 try
                 {
                     for (int i = 0; i < settings.TrasactionSize && !forceStopToken.IsCancellationRequested && !DataQueue.IsEmpty; i++)
                     {
                         if (DataQueue.TryDequeue(out T message))
                         {
                             await writerCore.ExecuteWriting(command, message, forceStopToken);
                         }
                     }
                     await transaction.CommitAsync(forceStopToken);
                 }
                 catch (Exception ex)
                 {
                     logger.Error(ex, "Error while writing messages!");
                     await transaction.RollbackAsync();
                 }
             }
             await Task.Delay(100);
         }
     }
 }
        public async Task <int> ExecuteTransactionAsync(Dictionary <string, object> sqlAndParameters, bool disposeConnection = true)
        {
            DbTransaction dbTransaction = null;

            try
            {
                await this.OpenDBConnectionAsync();

                dbTransaction = await base._dbConnection.BeginTransactionAsync();

                int affectedCollumnsNum = 0;

                foreach (KeyValuePair <string, object> sqlAndParameter in sqlAndParameters)
                {
                    affectedCollumnsNum += await base._dbConnection.ExecuteAsync(sqlAndParameter.Key, sqlAndParameter.Value, dbTransaction);
                }

                await dbTransaction.CommitAsync();

                return(affectedCollumnsNum);
            }
            catch (DbException e)
            {
                await dbTransaction?.RollbackAsync();

                disposeConnection = true;
                throw e;
            }
            catch (Exception e)
            {
                await dbTransaction?.RollbackAsync();

                disposeConnection = true;
                // TODO: Create a Transaction exception.
                throw e;
            }
            finally
            {
                _ = dbTransaction.DisposeAsync();

                if (disposeConnection)
                {
                    _ = base._dbConnection.DisposeAsync();
                }
            }
        }
Exemple #7
0
 /// <summary>
 /// Rollbacks the.
 /// </summary>
 public async Task RollbackAsync()
 {
     if (dbTransaction != null)
     {
         await dbTransaction.RollbackAsync();
     }
     Dispose();
 }
        /// <summary>
        /// imports unimported poem data from a locally accessible ganjoor SqlLite database
        /// </summary>
        /// <returns></returns>
        public async Task <RServiceResult <bool> > ImportLocalSQLiteDb()
        {
            try
            {
                SqliteConnectionStringBuilder connectionStringBuilder = new SqliteConnectionStringBuilder();
                connectionStringBuilder.DataSource = Configuration.GetSection("LocalSqliteImport")["FilePath"];
                using (SqliteConnection sqliteConnection = new SqliteConnection(connectionStringBuilder.ToString()))
                {
                    await sqliteConnection.OpenAsync();

                    IDbConnection dapper = sqliteConnection;
                    using (var sqlConnection = _context.Database.GetDbConnection())
                    {
                        await sqlConnection.OpenAsync();

                        foreach (var poet in await dapper.QueryAsync("SELECT * FROM poet ORDER BY id"))
                        {
                            int poetId = (int)poet.id;
                            if ((await _context.GanjoorPoets.Where(p => p.Id == poetId).FirstOrDefaultAsync()) != null)
                            {
                                continue;
                            }

                            DbTransaction transaction = await sqlConnection.BeginTransactionAsync();

                            try
                            {
                                using (var command = sqlConnection.CreateCommand())
                                {
                                    command.Transaction = transaction;
                                    command.CommandText =
                                        $"INSERT INTO GanjoorPoets (Id, Name, Description) VALUES (${poet.id}, N'{poet.name}', N'{poet.description}')";
                                    await command.ExecuteNonQueryAsync();
                                    await _ImportSQLiteCatChildren(command, dapper, poetId, 0, "", "");

                                    await transaction.CommitAsync();
                                }
                            }
                            catch (Exception exp2)
                            {
                                await transaction.RollbackAsync();

                                return(new RServiceResult <bool>(false, exp2.ToString()));
                            }
                        }
                    }
                }
            }
            catch (Exception exp)
            {
                return(new RServiceResult <bool>(false, exp.ToString()));
            }
            return(new RServiceResult <bool>(true));
        }
Exemple #9
0
        public async Task RollbackTransactionAsync(DbTransaction transaction)
        {
            DbConnection connection = transaction.Connection;
            await transaction.RollbackAsync();

            await connection.CloseAsync();

            await transaction.DisposeAsync();

            await connection.DisposeAsync();
        }
Exemple #10
0
 /// <summary>
 /// 异步回滚事务
 /// </summary>
 /// <returns></returns>
 public async Task RollbackAsync()
 {
     if (_dbTransaction?.Connection != null)
     {
         await _dbTransaction.RollbackAsync();
     }
     if (_dbContext.Database.CurrentTransaction != null)
     {
         await _dbContext.Database.CurrentTransaction.DisposeAsync();
     }
     HasCommitted = true;
 }
Exemple #11
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;
        }
Exemple #12
0
        /// <summary>
        /// 批量插入
        /// </summary>
        /// <param name="inputDto"></param>
        /// <returns></returns>
        public async Task CreateAsync(CreateGroupDto inputDto)
        {
            bool exist = await _groupRepository.Select.AnyAsync(r => r.Name == inputDto.Name);

            if (exist)
            {
                throw new LinCmsException("分组已存在,不可创建同名分组", ErrorCode.RepeatField);
            }

            LinGroup linGroup = Mapper.Map <LinGroup>(inputDto);

            using var conn = _freeSql.Ado.MasterPool.Get();
            await using DbTransaction transaction = await conn.Value.BeginTransactionAsync();

            try
            {
                long groupId = await _freeSql.Insert(linGroup).WithTransaction(transaction).ExecuteIdentityAsync();

                List <LinPermission> allPermissions = await _freeSql.Select <LinPermission>().WithTransaction(transaction).ToListAsync();

                List <LinGroupPermission> linPermissions = new List <LinGroupPermission>();
                inputDto.PermissionIds.ForEach(r =>
                {
                    LinPermission pdDto = allPermissions.FirstOrDefault(u => u.Id == r);
                    if (pdDto == null)
                    {
                        throw new LinCmsException($"不存在此权限:{r}", ErrorCode.NotFound);
                    }
                    linPermissions.Add(new LinGroupPermission(groupId, pdDto.Id));
                });

                await _freeSql.Insert <LinGroupPermission>()
                .WithTransaction(transaction)
                .AppendData(linPermissions)
                .ExecuteAffrowsAsync();

                await transaction.CommitAsync();
            }
            catch
            {
                await transaction.RollbackAsync();

                throw;
            }
        }
        public async Task RollbackAsync(CancellationToken cancellationToken)
        {
            ThrowIfTransactionNull();

            try
            {
                await transaction.RollbackAsync(cancellationToken);
            }
            finally
            {
                try
                {
                    transaction.Dispose();
                }
#pragma warning disable S2486 // Generic exceptions should not be ignored
                catch (Exception)
                {
                    // todo log
                }
#pragma warning restore S2486 // Generic exceptions should not be ignored

                transaction = null;
            }
        }
Exemple #14
0
 private async Task CommitOrRollbackTransactionAsync()
 {
     try
     {
         if (!_cancel)
         {
             if (_transaction != null)
             {
                 await _transaction.CommitAsync();
             }
         }
         else
         {
             if (_transaction != null)
             {
                 await _transaction.RollbackAsync();
             }
         }
     }
     finally
     {
         await ReleaseConnectionAsync();
     }
 }
        public async Task RollbackAsync(CancellationToken cancellationToken = default)
        {
            await _dbContextTransaction?.RollbackAsync(cancellationToken);

            await _dbTransaction?.RollbackAsync(cancellationToken);
        }
 public Task RollbackAsync(CancellationToken cancellationToken = default)
 {
     return(_transaction.RollbackAsync(cancellationToken));
 }
Exemple #17
0
 public async Task RollbackAsync(CancellationToken cancellationToken = default(CancellationToken))
 {
     await _transaction.RollbackAsync(cancellationToken);
 }