public async Task <IActionResult> SalvarOperacao([FromBody] OperacaoItem operacaoToSave) { if (_moduloContext.Set <OperacaoItem>().Any(e => e.Id_Operacao == operacaoToSave.Id_Operacao)) { _moduloContext.OperacaoItems.Update(operacaoToSave); } else { _moduloContext.OperacaoItems.Add(operacaoToSave); } //Create Integration Event to be published through the Event Bus var operacaoInclusaoEvent = new OperacaoInclusaoIE(operacaoToSave.Id_Operacao, operacaoToSave.Nome_Operacao, operacaoToSave.Id_Operacao); // Achieving atomicity between original Catalog database operation and the IntegrationEventLog thanks to a local transaction await _moduloIntegrationEventService.SaveEventAndOperacaoContextChangesAsync(operacaoInclusaoEvent, operacaoToSave); // Publish through the Event Bus and mark the saved event as published await _moduloIntegrationEventService.PublishThroughEventBusAsync(operacaoInclusaoEvent); return(CreatedAtAction(nameof(SalvarOperacao), operacaoToSave.Id_Operacao)); }
public async Task SaveEventAndOperacaoContextChangesAsync(IntegrationEvent evt, OperacaoItem operacaoToSave) { var strategy = _moduloContext.Database.CreateExecutionStrategy(); await strategy.ExecuteAsync(async() => { using (var transaction = _moduloContext.Database.BeginTransaction()) { try { await _moduloContext.SaveChangesAsync(); //Tratamento de Identity ((Events.OperacaoInclusaoIE)evt).OperacaoId = operacaoToSave.Id_Operacao; await _eventLogService.SaveEventAsync(evt, _moduloContext.Database.CurrentTransaction.GetDbTransaction()); transaction.Commit(); } catch (Exception ex) { transaction.Rollback(); var sqlException = ex.InnerException as System.Data.SqlClient.SqlException; throw new Exception(sqlException.Number + "::" + sqlException.Message); } } }); }