public async Task <IActionResult> CreateCityForCountry(int countryId, [FromBody] CityAddResource city) { if (city == null) { return(BadRequest()); } if (!ModelState.IsValid) { return(new UnprocessableEntityObjectResult(ModelState)); } if (!await _countryRepository.CountryExistAsync(countryId)) { return(NotFound()); } var cityModel = _mapper.Map <City>(city); _cityRepository.AddCityForCountry(countryId, cityModel); if (!await _unitOfWork.SaveAsync()) { throw new Exception("Error occurred when adding"); } var cityResource = Mapper.Map <CityResource>(cityModel); return(CreatedAtRoute("GetCityForCountry", new { countryId, cityId = cityModel.Id }, CreateLinksForCity(cityResource))); }
public async Task <IActionResult> CteateCityForCountry(int countryId, [FromBody] CityAddResource city) { if (city == null) { return(BadRequest()); } if (!await _countryRepository.CountryExistAsync(countryId)) { return(NotFound()); } var cityModel = _mapper.Map <City>(city); _cityRepository.AddCity(countryId, cityModel); if (!await _unitOfWork.SaveAsync()) { return(StatusCode(500, "保存错误")); } var cityResource = _mapper.Map <CityResource>(cityModel); return(CreatedAtRoute("GetCity", new { countryId, cityId = cityResource.Id }, cityResource)); }
public async Task <IActionResult> CreateCityForCountry(int countryId, [FromBody] CityAddResource city) { if (city == null) { return(BadRequest()); } //直接在方法里写验证逻辑 要求City的name属性值不可以是“中国” if (city.Name == "中国") { ModelState.AddModelError(nameof(city.Name), "城市的名称不可以叫中国"); } if (!ModelState.IsValid) { return(new UnprocessableEntityObjectResult(ModelState)); } if (!await _countryRepository.CountryExistAsync(countryId)) { return(NotFound()); } var cityModel = _mapper.Map <City>(city); _cityRepository.AddCityForCountry(countryId, cityModel); if (!await _unitOfWork.SaveAsync()) { return(StatusCode(500, "Error occurred when adding")); } var cityResource = _mapper.Map <CityResource>(cityModel); return(CreatedAtRoute("GetCity", new { countryId, cityId = cityModel.Id }, cityResource)); }