public async Task DeleteEventAndEmpresaPerfilContextChangesAsync(IntegrationEvent evt) { var strategy = _usuarioContext.Database.CreateExecutionStrategy(); await strategy.ExecuteAsync(async() => { using (var transaction = _usuarioContext.Database.BeginTransaction()) { try { EmpresaPerfilItem empresaPerfilItem = new EmpresaPerfilItem(); empresaPerfilItem.id_Empresa = ((Events.EmpresaPerfilExclusaoIE)evt).EmpresaId; empresaPerfilItem.id_Perfil = ((Events.EmpresaPerfilExclusaoIE)evt).PerfilId; await _usuarioContext.SaveChangesAsync(); await _eventLogService.SaveEventAsync(evt, _usuarioContext.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); } } }); }
public async Task <IActionResult> IncluirEmpresaPerfil([FromBody] EmpresaPerfilItem empresaPerfilToSave) { string msgRule = ""; EmpresaPerfilItem objItemEmpresa = _usuarioContext.EmpresaPerfilItems.Where(m => m.id_Empresa == empresaPerfilToSave.id_Empresa && m.id_Perfil == empresaPerfilToSave.id_Perfil).FirstOrDefault(); if (objItemEmpresa == null) { _usuarioContext.EmpresaPerfilItems.Add(empresaPerfilToSave); } else { objItemEmpresa.cod_Tipo = empresaPerfilToSave.cod_Tipo; _usuarioContext.EmpresaPerfilItems.Update(objItemEmpresa); } //Create Integration Event to be published through the Event Bus var empresaPerfilInclusaoEvent = new EmpresaPerfilInclusaoIE(empresaPerfilToSave.id_Empresa, empresaPerfilToSave.id_Perfil); try { // Achieving atomicity between original Catalog database operation and the IntegrationEventLog thanks to a local transaction await _usuarioIntegrationEventService.SaveEventAndEmpresaPerfilContextChangesAsync(empresaPerfilInclusaoEvent); } catch (Exception e) { //Validações das CONSTRAINTS do BANCO if (ruleValidaEmpresaPerfilPK(e.Message, ref msgRule)) { return(BadRequest(msgRule)); } else { return(BadRequest(e.Message)); } } // Publish through the Event Bus and mark the saved event as published await _usuarioIntegrationEventService.PublishThroughEventBusAsync(empresaPerfilInclusaoEvent); return(CreatedAtAction(nameof(IncluirEmpresaPerfil), null)); }