public async Task <bool> Commit(bool state = true)
        {
            if (!state)
            {
                await dbContextTransaction.RollbackAsync();

                return(state);
            }

            bool commitState;

            try
            {
                await SaveChangesAsync();

                commitState = true;
            }
            catch
            {
                commitState = false;
            }

            if (commitState)
            {
                await dbContextTransaction.CommitAsync();
            }
            else
            {
                await dbContextTransaction.RollbackAsync();
            }

            return(commitState);
        }
 public async Task CommitAsync(CancellationToken cancellationToken = default)
 {
     try
     {
         await _transaction.CommitAsync(cancellationToken);
     }
     catch
     {
         await _transaction.RollbackAsync(cancellationToken);
     }
 }
 public async Task RollbackTransactionAsync()
 {
     if (HasActiveTransaction)
     {
         try
         {
             await _currentTransaction.RollbackAsync();
         }
         finally
         {
             _currentTransaction.Dispose();
             _currentTransaction = null;
         }
     }
 }
 public async ValueTask DisposeAsync()
 {
     if (!_commited)
     {
         await _transaction.RollbackAsync();
     }
 }
Example #5
0
 async Task IUow.Rollback()
 {
     if (_transaction != null)
     {
         await _transaction.RollbackAsync(_token);
     }
 }
Example #6
0
        public async Task RollbackTransactionAsync()
        {
            if (_transaction == null)
                throw new InvalidOperationException($"You did not start a Transaction by calling \"{nameof(StartTransactionAsync)}\" method.");

            await _transaction.RollbackAsync();
        }
        public async Task RollbackTransactionAsync()
        {
            await Transaction.RollbackAsync();

            Transaction?.Dispose();
            Transaction = null;
        }
Example #8
0
 public void Rollback()
 {
     if (_dbContextTransaction != null)
     {
         _dbContextTransaction.RollbackAsync().Wait();
     }
 }
        public async Task <IActionResult> Create(Employee employee)
        {
            if (ModelState.IsValid)
            {
                IDbContextTransaction transaction = await _repository.BeginTransactionAsync(IsolationLevel.ReadCommitted);

                try
                {
                    employee.DepartmentId = 1;

                    object[] primaryKeys = await _repository.InsertAsync(employee);


                    long            employeeId      = (long)primaryKeys[0];
                    EmployeeHistory employeeHistory = new EmployeeHistory()
                    {
                        EmployeeId   = employeeId,
                        DepartmentId = employee.DepartmentId,
                        EmployeeName = employee.EmployeeName
                    };

                    await _repository.InsertAsync(employeeHistory);

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

                return(RedirectToAction(nameof(Index)));
            }
            return(View(employee));
        }
Example #10
0
        public async Task <ActionResult <Cake> > Put(Cake cake)
        {
            using (IDbContextTransaction dbContextTransaction = context.Database.BeginTransaction())
            {
                try
                {
                    try
                    {
                        cake.PreparationDate      = DateTime.Now;
                        context.Entry(cake).State = EntityState.Modified;
                        await context.SaveChangesAsync();

                        await dbContextTransaction.CommitAsync();

                        return(Ok(cake));
                    }
                    catch (Exception ex)
                    {
                        await dbContextTransaction.RollbackAsync();

                        return(BadRequest(new RetornoRequisicao {
                            Mensagem = ex.Message, Sucesso = false
                        }));
                    }
                }
                catch (Exception ex)
                {
                    var retorno = new RetornoRequisicao()
                    {
                        Mensagem = ex.Message, Sucesso = false
                    };
                    return(BadRequest(retorno));
                }
            }
        }
Example #11
0
        public async Task <Config> Handle(UpdateConfigCommand request, CancellationToken cancellationToken)
        {
            await using IDbContextTransaction transaction = _configContext.Database.BeginTransaction();
            try
            {
                (Config config, ConfigElement root, ConfigElement[] all)configSource = await _configService.GetConfigElement(
                    () => _configService.GetConfig(request, EnvironmentRole.Editor, cancellationToken),
                    cancellationToken);

                Config config = new Config(request.ConfigCode, configSource.config.Environment,
                                           request.VersionFrom);
                ObjectConfigReader reader        = new ObjectConfigReader(config);
                ConfigElement      configElement = await reader.Parse(request.Data);

                Compare(configSource.root, configElement);

                await _configContext.SaveChangesAsync(cancellationToken);

                await _cacheService.UpdateJsonConfig(configSource.config.ConfigId, request.Data, cancellationToken);

                await transaction.CommitAsync(cancellationToken);

                return(configSource.config);
            }
            catch (Exception ex)
            {
                await transaction.RollbackAsync(cancellationToken);

                _logger.LogError(ex, "{request} data:{Data}", request, request.Data);
                throw;
            }
        }
Example #12
0
 public async Task RollbackAsync()
 {
     if (_isTransactionStarted && _dbContextTransaction != null)
     {
         await _dbContextTransaction?.RollbackAsync();
     }
 }
Example #13
0
        /// <summary>
        /// 事务执行 - Async
        /// </summary>
        /// <param name="dbContext"></param>
        /// <param name="func"></param>
        /// <returns></returns>
        public static async Task ExecuteTransactionAsync <TDbContext>(this TDbContext context, Func <TDbContext, IDbConnection, IDbTransaction, Task> func, IsolationLevel isolationLevel = IsolationLevel.ReadCommitted)
            where TDbContext : DbContext
        {
            if (func == null)
            {
                throw new ArgumentNullException(nameof(func));
            }

            IDbContextTransaction tran = await context.Database.BeginTransactionAsync(isolationLevel);

            try
            {
                DbConnection  connection  = context.Database.GetDbConnection();
                DbTransaction transaction = tran.GetDbTransaction();
                await func(context, connection, transaction);

                await tran.CommitAsync();
            }
            catch (Exception ex)
            {
                await tran?.RollbackAsync();

                throw;
            }
            finally
            {
                tran?.Dispose();
            }
        }
Example #14
0
 public async Task RollbackTransactionAsync()
 {
     if (_transaction != null)
     {
         await _transaction.RollbackAsync();
     }
 }
Example #15
0
        public async Task CommitAsync(CancellationToken cancellationToken = default)
        {
            if (_context == null)
            {
                throw new ArgumentNullException(nameof(_context));
            }
            if (_dbContextTransaction == null)
            {
                throw new ArgumentNullException(nameof(_dbContextTransaction));
            }
            try
            {
                await _context.SaveChangesAsync(cancellationToken);

                await _dbContextTransaction.CommitAsync(cancellationToken);
            }
            catch
            {
                await _dbContextTransaction.RollbackAsync(cancellationToken);

                throw;
            }
            finally
            {
                if (_dbContextTransaction != null)
                {
                    await _dbContextTransaction.DisposeAsync();

                    _dbContextTransaction = null;
                }
            }
        }
Example #16
0
        public async Task RoleBack()
        {
            await _dbContextTransaction.RollbackAsync();

            _dbContextTransaction.Dispose();
            _dbContextTransaction = null;
        }
Example #17
0
 public async Task RollbackAsync(CancellationToken cancellationToken = default)
 {
     if (!_existingTransaction)
     {
         await _transaction.RollbackAsync();
     }
 }
Example #18
0
        public async Task <bool> CommitAsync()
        {
            using (IDbContextTransaction transaction = _context.Database.BeginTransaction())
            {
                try
                {
                    var changes = await _context.SaveChangesAsync();

                    await transaction.CommitAsync();

                    return(true);
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.Message);
                    await transaction.RollbackAsync();

                    return(false);
                }
                finally
                {
                    //usar em banco de dados relacional e que nao seja em memoria
                    //_contextEntity.Database.GetDbConnection().Close();
                }
            }
        }
Example #19
0
 public async Task Rollback()
 {
     if (transaction != null)
     {
         await transaction.RollbackAsync();
     }
 }
        public async override Task Invoke(AspectContext context, AspectDelegate next)
        {
            DbContext dbContext = context.ServiceProvider.GetService(_dbContextType) as DbContext;

            if (dbContext.Database.CurrentTransaction == null)
            {
                using IDbContextTransaction transaction = await dbContext.Database.BeginTransactionAsync();

                try
                {
                    await next(context);

                    await transaction.CommitAsync();

                    //dbContext.Database.CommitTransaction();
                }
                catch (Exception ex)
                {
                    await transaction.RollbackAsync();

                    //dbContext.Database.RollbackTransaction();
                    throw ex;
                }
            }
            else
            {
                await next(context);
            }
        }
Example #21
0
        // Map model to order
        // Set date to order
        // Calculate total cost and OrderProduct prices
        // Insert order
        // Set orderId to orderProducts
        // Insert orderProducts
        public async Task <DataResult <int> > CreateOrder(OrderCreationalModel orderCreationalModel)
        {
            using (IDbContextTransaction transaction = await _orderRepository.BeginTransactionAsync())
            {
                try
                {
                    Order order = _orderMapper.MapBackToEntity(orderCreationalModel);
                    order.OrderDate = DateTime.UtcNow;

                    order = await _orderRepository.AddAsync(order);

                    await _orderRepository.SaveAsync();

                    foreach (OrderProductModel orderProductModel in orderCreationalModel.OrderProductModels)
                    {
                        Result orderProductAddResult = await AddOrderProductAsync(order, orderProductModel);

                        if (orderProductAddResult.ResponseMessageType == ResponseMessageType.Error)
                        {
                            await transaction.RollbackAsync();

                            return(new DataResult <int>
                            {
                                ResponseMessageType = ResponseMessageType.Error
                            });
                        }
                    }

                    _orderRepository.Update(order);
                    await _orderRepository.SaveAsync();

                    await transaction.CommitAsync();

                    return(new DataResult <int>
                    {
                        Data = order.Id,
                        ResponseMessageType = ResponseMessageType.Success
                    });
                }
                catch (Exception)
                {
                    await transaction.RollbackAsync();

                    throw;
                }
            }
        }
Example #22
0
        public async Task RollbackAsync(CancellationToken cancellationToken = default(CancellationToken))
        {
            CheckNotNull(_dbTransaction);

            await _dbTransaction.RollbackAsync(cancellationToken);

            _unitOfWorkStatus.IsStartingUow = false;
        }
            public async ValueTask DisposeAsync()
            {
                await _transaction.RollbackAsync().ConfigureAwait(false);

                await _transaction.DisposeAsync().ConfigureAwait(false);

                _scope.Dispose();
            }
Example #24
0
        public async Task RollbackAsync(CancellationToken cancellationToken = default)
        {
            await _transaction.RollbackAsync();

            await _transaction.DisposeAsync();

            _transaction = null;
        }
Example #25
0
        public async Task RollbackTransactionAsync()
        {
            await _dbTransaction.RollbackAsync();

            await _dbTransaction.DisposeAsync();

            _dbTransaction = null;
        }
Example #26
0
        public async Task RollbackAsync()
        {
            ValidateTransaction();

            await transaction.RollbackAsync();

            await DisposeTransactionAsync();
        }
Example #27
0
 public async Task RollbackAsync()
 {
     if (_transaction != null)
     {
         await _transaction.RollbackAsync();
         await DisposableAsync();
     }
 }
Example #28
0
 public async Task <IResult> RollbackTransactionAsync(CancellationToken cancellationToken = default)
 {
     if (_transaction != null)
     {
         await _transaction.RollbackAsync(cancellationToken).ConfigureAwait(false);
     }
     return(Result.Ok());
 }
Example #29
0
 /// <summary>
 /// Cancelar a transação
 /// </summary>
 /// <param name="cancellationToken">Token de cancelamento</param>
 public async Task RollBackAsync(CancellationToken cancellationToken = default)
 {
     await _transaction.RollbackAsync(cancellationToken)
     .ContinueWith((tsk) =>
     {
         TransactionStarted = false;
     });
 }
Example #30
0
        public Task RollbackAsync(CancellationToken token = default)
        {
            if (TransactionId == Guid.Empty)
            {
                return(Task.CompletedTask);
            }

            return(_transaction.RollbackAsync(token));
        }