public async Task <IActionResult> CreateCountry([FromBody] CountryAddDto countryDto) { if (countryDto == null) { return(BadRequest()); } if (!ModelState.IsValid) { return(new UnprocessableEntityObjectResult(ModelState)); } var country = _mapper.Map <Country>(countryDto); _countryRepository.AddCountry(country); if (!await _unitOfWork.SaveAsync()) { throw new Exception("Error occured when adding"); } var countryAddDto = Mapper.Map <CountryDto>(country); //hateos return(CreatedAtRoute("GetCountry", new { }, countryAddDto)); }
public async Task <IRepositoryResult> AddCountry([FromBody] CountryAddDto country) { var repositoryResult = await _countryBusiness.AddCountry(country); var result = ResponseHandler.GetResult(repositoryResult); return(result); }
public async Task <IActionResult> Post([FromBody] CountryAddDto countryAddDto) { if (!ModelState.IsValid) { return(BadRequest(ModelState)); } if (await _countryRepository.GetAll().AnyAsync(c => c.EnglishName == countryAddDto.EnglishName)) { ModelState.AddModelError(nameof(CountryDto.EnglishName), $"已经存在名为 {countryAddDto.EnglishName} 的国家"); return(BadRequest(ModelState)); } var country = _mapper.Map <Country>(countryAddDto); _countryRepository.Insert(country); await _unitOfWork.SaveChangesAsync(); var countryDto = _mapper.Map <CountryDto>(country); // CreatedAtAction 会返回绝对路径,实际项目中绝对路径会被Api网关转换。 //return CreatedAtAction("Get", new { id = country.Id }, countryDto); return(Created(new Uri($"{Request.Path}/{countryDto.Id}", UriKind.Relative), countryDto)); }
public async Task <IRepositoryActionResult> AddCountry(CountryAddDto country) { try { if (country == null) { return(RepositoryActionResult.GetRepositoryActionResult(message: "Invalid Data")); } var newCountry = Mapper.Map <CountryAddDto, Country>(country); var addedCountry = UnitOfWork.Repository.Add(newCountry); var isSaved = await UnitOfWork.SaveChanges() > 0; if (isSaved) { return(RepositoryActionResult.GetRepositoryActionResult(result: addedCountry, status: RepositoryActionStatus.Created, message: "Saved Successfully")); } return(RepositoryActionResult.GetRepositoryActionResult(status: RepositoryActionStatus.NothingModified, message: "Save Failed")); } catch (Exception e) { return(RepositoryActionResult.GetRepositoryActionResult(exception: e, message: "Something went error", status: RepositoryActionStatus.Error)); } }