public async Task <Incidence> AddOrUpdate(SafetyIncidenceDto resourceParameter) { if (resourceParameter == null) { throw new ArgumentNullException("resourceParameter cannot be null."); } var injuryStatus = await _context.InjuryStats .AsNoTracking() .FirstOrDefaultAsync(x => x.InjuryStat1 == resourceParameter.InjuryStatId) .ConfigureAwait(false); var injuryStatusName = injuryStatus?.InjuryStat1 ?? ""; var isClosed = resourceParameter?.IsClosed ?? false; var hasFmTips = !resourceParameter?.IsFmTipsCompleted ?? false; if (injuryStatusName.ToLower().Contains("recordable") && isClosed && hasFmTips) { throw new OperationCanceledException( "FM Tips must be completed first before changing status to close." ); } var data = _mapper.Map <Incidence>(resourceParameter); await using var transaction = await _context.Database .BeginTransactionAsync() .ConfigureAwait(false); try { var isRecordable = resourceParameter.Id > 0 && await IsRecordable(resourceParameter.Id).ConfigureAwait(false); var entity = _context.Incidences.Update(data); await _context.SaveChangesAsync().ConfigureAwait(false); await transaction.CommitAsync().ConfigureAwait(false); if (isRecordable && resourceParameter.Id > 0) { await SendRecordableEmail(entity.Entity).ConfigureAwait(false); } return(entity.Entity); } catch (Exception e) { await transaction.RollbackAsync().ConfigureAwait(false); throw new Exception(e.Message); } }
public async Task <IActionResult> AddOrUpdate(SafetyIncidenceDto resourceParameter) { try { var data = await _service.AddOrUpdate(resourceParameter).ConfigureAwait(false); return(Ok(data)); } catch (Exception e) { return(BadRequest(e.Message)); } }