public IActionResult Add([FromBody] ProductCategoryForPostDto productCategoryDto) { try { if (productCategoryDto == null) { return(BadRequest()); } if (!ModelState.IsValid) { return(BadRequest(ModelState)); } var productCategory = Mapper.Map <ProductCategory>(productCategoryDto); _productCategoryRepository.AddProductCategory(productCategory); if (!_productCategoryRepository.Save()) { _logger.LogCritical($"Exception while adding a new product category."); return(StatusCode(500, "A problem happened while handling your request.")); } var productCategoryDtoResult = Mapper.Map <ProductCategoryDto>(productCategory); return(CreatedAtRoute("GetProductCategory", new { id = productCategoryDtoResult.Id }, productCategoryDtoResult)); } catch (Exception ex) { _logger.LogCritical($"Exception while adding a new product category.", ex); return(StatusCode(500, "A problem happened while handling your request.")); } }
public IActionResult Update(int id, [FromBody] ProductCategoryForPostDto productCategoryDto) { if (productCategoryDto == null) { return(BadRequest()); } if (!ModelState.IsValid) { return(BadRequest(ModelState)); } var productCategoryEntity = _productCategoryRepository.GetProductCategory(id); if (productCategoryEntity == null) { return(NotFound()); } Mapper.Map(productCategoryDto, productCategoryEntity); if (!_productCategoryRepository.Save()) { return(StatusCode(500, "A problem happened while handling your request.")); } return(NoContent()); }
public void When_validating_the_state_of_a_product_category_with_an_invalid_name_it_should_return_an_error(string name) { // Arrange var model = new ProductCategoryForPostDto(); model.Name = name; var context = new ValidationContext(model, null, null); var result = new List <ValidationResult>(); // Act var valid = Validator.TryValidateObject(model, context, result, true); // Assert valid.Should().BeFalse(); result.Should().HaveCount(1); var failure = result.First(); failure.MemberNames.Should().ContainSingle("Name"); }
public void When_updating_a_product_category_the_query_for_that_id_should_return_the_updated_element() { // Arrange var controller = new ProductCategoriesController(_logger, _repository); var originalElement = ValidDataHelper.GetValidProductCategoryDto(controller); originalElement.Name = $"UpdatedValue for Id={originalElement.Id}"; var updatedValue = new ProductCategoryForPostDto() { Name = originalElement.Name }; // Act var result = controller.Update(originalElement.Id, updatedValue); var getResult = controller.GetProductCategory(originalElement.Id); var retrievedValue = getResult.ValidateResponseAndCastTo <ProductCategoryDto, OkObjectResult> ((int)HttpStatusCodes.Ok); // Asset result.Should().BeOfType <NoContentResult>(); retrievedValue.ShouldBeEquivalentTo(originalElement); }