public async Task <IActionResult> PutIngrType(int id, IngrType ingrType) { if (id != ingrType.Id) { return(BadRequest()); } _context.Entry(ingrType).State = EntityState.Modified; try { await _context.SaveChangesAsync(); } catch (DbUpdateConcurrencyException) { if (!IngrTypeExists(id)) { return(NotFound()); } else { throw; } } return(NoContent()); }
public async Task <IActionResult> PutRecord(int id, RecordViewModel recordVM) { var oldRecord = _context.Records.Find(id); if (oldRecord == null) { return(NotFound()); } oldRecord.DishId = recordVM.DishId; oldRecord.Grams = recordVM.Grams; try { await _context.SaveChangesAsync(); } catch (DbUpdateConcurrencyException) { if (!RecordExists(id)) { return(NotFound()); } else { throw; } } return(NoContent()); }
public async Task <IActionResult> PutDish([FromRoute] int id, [FromRoute] string Name, [FromBody] IEnumerable <ComponentViewModel> componentVMs) { var dish = _context.Dishes.Find(id); if (dish == null) { return(NotFound()); } dish.Name = Name; var oldComponents = _context.Components.Where(c => c.DishId == id).ToList(); _context.Components.RemoveRange(oldComponents); foreach (var comp in componentVMs) { if (!(_context.Ingredients.Any(i => i.Id == comp.IngredientId))) { return(BadRequest()); } Component component = new Component() { DishId = dish.Id, IngredientId = comp.IngredientId, Grams = comp.Grams }; _context.Components.Add(component); } await _context.SaveChangesAsync(); var relatedComponents = _context.Components.Where(c => c.DishId == dish.Id); int totalWeight = 0; int totalKcals = 0; foreach (var comp in relatedComponents) { int kcalsPer100g = _context.Ingredients.Find(comp.IngredientId).KcalsPer100g; int kcals = comp.Grams * kcalsPer100g / 100; totalKcals += kcals; totalWeight += comp.Grams; } dish.KcalsPer100g = 100 * totalKcals / totalWeight; _context.Dishes.Update(dish); try { await _context.SaveChangesAsync(); } catch (DbUpdateConcurrencyException) { if (!DishExists(id)) { return(NotFound()); } else { throw; } } return(NoContent()); }