public async Task <IActionResult> Delete(long id, string userId) { var categoryToDelete = await _context.Categories.FindAsync(id); if (categoryToDelete == null) { _logger.LogWarning("Attempt to delete non-existing category of ID {CategoryId}", id); return(NotFound()); } try { var categoryAuditTrail = new CategoryAuditTrail { CategoryId = categoryToDelete.Id, Name = categoryToDelete.Name, ActionTypeId = (long)SD.EntityActionType.Delete, PerformedBy = userId, PerformedDate = DateTime.Now }; _context.CategoryAuditTrails.Add(categoryAuditTrail); _context.Categories.Remove(categoryToDelete); await _context.SaveChangesAsync(); } catch (Exception ex) { _logger.LogError(ex, "Error deleting {@Category} from database", categoryToDelete); return(StatusCode(Convert.ToInt32(HttpStatusCode.InternalServerError))); } return(NoContent()); }
public async Task <ActionResult <Boolean> > Update(long id, Category category) { if (id != category.Id) { return(BadRequest()); } var existingCategory = await _context.Categories.FirstOrDefaultAsync(c => c.Name.ToLower() == category.Name.Trim().ToLower()); try { if (existingCategory == null) { var oldCategoryValues = await _context.Categories.AsNoTracking().FirstAsync(c => c.Id == category.Id); var categoryAuditTrail = new CategoryAuditTrail { CategoryId = oldCategoryValues.Id, Name = oldCategoryValues.Name, ActionTypeId = (long)SD.EntityActionType.Update, PerformedBy = category.UpdatedBy, PerformedDate = category.UpdatedAt }; _context.CategoryAuditTrails.Add(categoryAuditTrail); _context.Entry(category).State = EntityState.Modified; await _context.SaveChangesAsync(); return(true); } else { _logger.LogWarning("Attempt to update product category {@Category} failed due to duplicate category {@ExistingCategory}", category, existingCategory); return(false); } } catch (Exception ex) { _logger.LogError(ex, "Error updating product category {@Category}", category); return(false); } }