public IHttpActionResult CreateProduct(ProductModel product) { if (!ModelState.IsValid) { return BadRequest(ModelState); } var category = this.data.Categories.All().Where(c => c.Name == product.Category).FirstOrDefault(); if (category == null) { return BadRequest("Invalid category"); } Product newProduct = new Product() { Description = product.Description, Name = product.Name, Category = category, Price = product.Price, Size = product.Size, SizeUnit = (SizeUnit)Enum.Parse(typeof(SizeUnit), product.SizeUnit) }; this.data.Products.Add(newProduct); this.data.SaveChanges(); product.Id = newProduct.Id; return Ok(product); }
public IHttpActionResult Update(int id, ProductModel product) { if (!ModelState.IsValid) { return BadRequest(ModelState); } var existingProduct = this.data.Products.All().FirstOrDefault(p => p.Id == id); if (existingProduct == null) { return BadRequest("Such product doesn't exist!"); } existingProduct.Name = product.Name; existingProduct.Description = product.Description; existingProduct.Price = product.Price; existingProduct.Size = product.Size; var category = this.data.Categories.All().Where(c => c.Name == c.Name).FirstOrDefault(); if (category == null) { return BadRequest("Invalid category"); } existingProduct.Category = category; existingProduct.SizeUnit = (SizeUnit)Enum.Parse(typeof(SizeUnit), product.SizeUnit); this.data.SaveChanges(); product.Id = id; return Ok(product); }