public async Task <ActionResult <CostCenterVM> > UpdateCostCenter(int id, CostCenterVM costcenterVM) { try { if (id != costcenterVM.CostCenter.Id) { return(BadRequest("CostCenter ID mismatch")); } // Add custom model validation error CostCenter costcenter = await costcenterRepository.GetCostCenterByname(costcenterVM.CostCenter); if (costcenter != null) { ModelState.AddModelError("Name", $"CostCenter name: {costcenterVM.CostCenter.Name} already in use"); return(BadRequest(ModelState)); } var costcenterToUpdate = await costcenterRepository.GetCostCenter(id); if (costcenterToUpdate == null) { return(NotFound($"CostCenter with Id = {id} not found")); } await costcenterRepository.UpdateCostCenter(costcenterVM); return(CreatedAtAction(nameof(GetCostCenter), new { id = costcenterVM.CostCenter.Id }, costcenterVM)); } catch (DbUpdateException Ex) { return(StatusCode(StatusCodes.Status500InternalServerError, Ex.InnerException.Message)); } }