public IHttpActionResult Delete([FromUri] DateTime dateRangeStart, [FromUri] DateTime dateRangeEnd, [FromUri] List <string> salesAreaNames) { var messages = ValidateForDelete(dateRangeStart, dateRangeEnd, salesAreaNames); foreach (var message in messages) { ModelState.AddModelError(message.Key, message.Value); } if (!ModelState.IsValid) { return(BadRequest(ModelState)); } // broadcast day var defaultBroadcastStartTime = new TimeSpan(6, 0, 0); var defaultBroadcastEndTime = defaultBroadcastStartTime.Subtract(new TimeSpan(0, 0, 1)); var broadcastStartDateTime = dateRangeStart.Date.Add(defaultBroadcastStartTime); var broadcastEndDateTime = dateRangeEnd.Date.AddDays(1).Add(defaultBroadcastEndTime); var scheduledDatesRange = new DateTimeRange(broadcastStartDateTime, broadcastEndDateTime); var breaks = _breakRepository.Search(scheduledDatesRange, salesAreaNames).ToList(); if (!breaks.Any()) { return(NotFound()); } var breakIdsToDelete = new HashSet <Guid>(); var breakExtRefsToDelete = new List <string>(); foreach (var oneBreak in breaks) { breakIdsToDelete.Add(oneBreak.Id); breakExtRefsToDelete.Add(oneBreak.ExternalBreakRef); } // load spots and schedules to be updated var spotsToDelete = _spotRepository.FindByExternalBreakNumbers(breakExtRefsToDelete); var schedulesToUpdate = _scheduleRepository.FindByBreakIds(breakIdsToDelete); // delete spots first and persist changes if (spotsToDelete.Any()) { _spotRepository.Delete(spotsToDelete.Select(s => s.Uid)); _spotRepository.SaveChanges(); } _breakRepository.Delete(breakIdsToDelete.ToList()); foreach (var schedule in schedulesToUpdate) { schedule.Breaks = schedule.Breaks.Where(b => !breakIdsToDelete.Contains(b.Id)).ToList(); _scheduleRepository.Update(schedule); _scheduleRepository.SaveChanges(); } return(Ok()); }