public IHttpActionResult Delete(int id) { if (id <= 0) { ModelState.AddModelError(nameof(id), "Please specify positive delivery capping group id"); return(BadRequest(ModelState)); } if (_repository.Get(id) is null) { return(NotFound()); } var runs = _runRepository.GetRunsByDeliveryCappingGroupId(id).ToList(); var runsWithDCG = runs.Where(x => _notFinishedRunStatuses.Contains(x.RunStatus)); if (runsWithDCG.Any()) { ModelState.AddModelError(nameof(id), $"Delivery capping group with id: {id} is used in runs with status 'In Progress' / 'Not Started'.{Environment.NewLine}" + $"Run ids: {string.Join(", ", runsWithDCG.Select(x => x.Id))}" ); return(BadRequest(ModelState)); } for (int i = 0; i < runs.Count; i++) { runs[i].CampaignsProcessesSettings = runs[i].CampaignsProcessesSettings .Select(x => { if (x.DeliveryCappingGroupId == id) { x.DeliveryCappingGroupId = 0; } return(x); }) .Where(x => !x.IsEmpty) .ToList(); } _runRepository.UpdateRange(runs); _repository.Delete(id); return(this.NoContent()); }