// Loop throught and update necessary fields
        private Product UpdateExistingResource(Product existingProduct, ProductUpdateResource updatedProduct)
        {
            var result = existingProduct;

            foreach (var item in updatedProduct.ToDictionary())
            {
                var key   = item.Key;
                var value = item.Value;
                if (value is bool == false && value != null && value is int == false)
                {
                    result.GetType().GetProperty(key).SetValue(result, value, null);
                }
            }
            return(result);
        }
示例#2
0
        public async Task <IActionResult> UpdateProduct(int id, [FromBody] ProductUpdateResource productUpdate)
        {
            if (productUpdate == null)
            {
                return(BadRequest());
            }
            if (!ModelState.IsValid)
            {
                return(new UnprocessableEntityObjectResult(ModelState));
            }
            var product = await _productRepository.GetProductByIdAsync(id);

            if (product == null)
            {
                return(NotFound());
            }
            _mapper.Map(productUpdate, product);
            if (!await _unitOfWork.SaveAsync())
            {
                throw new Exception($"Updating product {id} failed when saving.");
            }
            return(NoContent());
        }
        public async Task <IActionResult> PutAsync(int id, [FromBody] ProductUpdateResource resource)
        {
            var existingProduct = await _productRepo.FindByIdAsync(id);

            if (existingProduct == null)
            {
                return(NotFound());
            }
            var updatedProduct = UpdateExistingResource(existingProduct, resource);

            try
            {
                _productRepo.Update(updatedProduct);
                await _productRepo.SaveChangeAsync();

                return(Ok(new { message = "Updated" }));
            }
            catch (Exception ex)
            {
                return(BadRequest(new List <string> {
                    ex.Message
                }));
            }
        }