private Food parseFoodDTO(FoodDTO dto) { int calories = 0; double sugar = 0; double fat = 0; double saturates = 0; double salt = 0; dto.Name = dto.Name.Trim(); dto.Description = dto.Description.Trim(); if(dto.Calories != "" && !int.TryParse(dto.Calories, out calories)) { throw new ValidationException("Calories is not a number."); } if (dto.Sugar != "" && !double.TryParse(dto.Sugar, out sugar)) { throw new ValidationException("Sugar is not a number."); } if (dto.Fat != "" && !double.TryParse(dto.Fat, out fat)) { throw new ValidationException("Fat is not a number."); } if (dto.Saturates != "" && !double.TryParse(dto.Saturates, out saturates)) { throw new ValidationException("Saturates is not a number."); } if (dto.Salt != "" && !double.TryParse(dto.Salt, out salt)) { throw new ValidationException("Salt is not a number."); } return new Food() { Name = dto.Name, Category = dto.Category, Description = dto.Description, Calories = calories, Sugars = sugar, Fat = fat, Saturates = saturates, Salt = salt }; }
public FoodDTO GetInputs() { FoodDTO dto = new FoodDTO() { Name = FoodItemView.FoodName, Category = FoodItemView.Category, Description = FoodItemView.Description, Calories = FoodItemView.Calories, Sugar = FoodItemView.Sugar, Fat = FoodItemView.Fat, Saturates = FoodItemView.SatFat, Salt = FoodItemView.Salt }; return dto; }
public Food AddFood(FoodDTO dto) { Food newFood = parseFoodDTO(dto); Validator.ValidateObject(newFood, new ValidationContext(newFood), true); //Check the food doesn't already exist in the database if (UnitOfWork.FoodRepository.GetAll().Where(x => x.Name.ToLower().Equals(newFood.Name.ToLower())).Any()) { throw new ValidationException("This food already exists."); } //Add the food to the database UnitOfWork.FoodRepository.Add(newFood); UnitOfWork.Save(); return newFood; }
public void EditFood(FoodDTO dto, Food food) { Food editedFood = parseFoodDTO(dto); Validator.ValidateObject(editedFood, new ValidationContext(editedFood), true); //if the name has changed check that there isn't an existing food with the new name if(dto.Name.ToLower() != food.Name.ToLower() && UnitOfWork.FoodRepository.GetAll().Where(x => x.Name.ToLower().Equals(dto.Name.ToLower())).Any()) { throw new ValidationException("A food with this name already exists."); } food.Update(editedFood); //Add the food to the database UnitOfWork.FoodRepository.Edit(food); UnitOfWork.Save(); }