public async Task <IActionResult> RemoveCitiesFromCountry([FromForm] RemoveCitiesFromCountryVM country) { if (country.CountryId == Guid.Empty) { ModelState.AddModelError(string.Empty, "Unexpected error occurred: The ID was blank."); return(BadRequest(ModelState)); } var result = await _service.RemoveCitiesFromCountry(country); if (result.Message == ActionMessages.Updated) { var cities = country.CitiesId.Count > 1 ? "cities" : "city"; return(RedirectToAction(nameof(Details), new { id = result.Country.Id, message = $"The requested {cities} were successfully removed from {result.Country.Name}." })); } else if (result.Message == ActionMessages.NotFound) { ModelState.AddModelError(string.Empty, $"Not country was found with ID: {country.CountryId}."); return(NotFound(ModelState)); } else { ModelState.AddModelError(string.Empty, $"Unexpected error occurred: The action {result.Message.ToString()}."); return(BadRequest(ModelState)); } }
public async Task <CountryWithMessage> RemoveCitiesFromCountry(RemoveCitiesFromCountryVM country) { try { if (country.CountryId == Guid.Empty) { throw new Exception("Unexpected error occurred: CountryId was blank."); } if (country.CitiesId == null || country.CitiesId.Count == 0) { throw new Exception("Unexpected error occurred: No ID's were found in list."); } var original = await _db.Countries.Include(x => x.Cities).FirstOrDefaultAsync(x => x.Id == country.CountryId); if (original == null) { return(new CountryWithMessage { Message = ActionMessages.NotFound }); } foreach (var cityId in country.CitiesId) { var city = await _db.Cities.FirstOrDefaultAsync(x => x.Id == cityId); if (original.Cities.Contains(city)) { original.Cities.Remove(city); } } await _db.SaveChangesAsync(); return(new CountryWithMessage { Country = original, Message = ActionMessages.Updated }); } catch (Exception ex) { throw new NullReferenceException(ex.Message, ex.InnerException); } }