public void UpdatePatch(Guid id, PatchProduct updateProduct) { var findProduct = _context.Products.Find(id); foreach (var item in updateProduct.GetType().GetProperties()) { var key = item.Name; var value = item.GetValue(updateProduct, null); if (key == "ImageFile" && value != null) { File.Delete(findProduct.Image); string fileExt = System.IO.Path.GetExtension(updateProduct.ImageFile.FileName); string namePath = "Upload\\" + Guid.NewGuid().ToString() + fileExt; FileStream fileStream = File.Create(namePath); updateProduct.ImageFile.CopyTo(fileStream); fileStream.Flush(); fileStream.Close(); findProduct.Image = namePath; continue; } if (value != null) { findProduct.GetType().GetProperty(key).SetValue(findProduct, value); } } _context.SaveChanges(); }
public IActionResult Patch(Guid id, [FromForm] PatchProduct updateProduct) { try { _services.UpdatePatch(id, updateProduct); return(Ok()); } catch { throw; } }