Beispiel #1
0
        /// <summary>
        /// Updates an existing food item in the database.
        /// Updates the total calories for the diary entry the food item belongs to.
        /// </summary>
        /// <param name="id"></param>
        /// <param name="foodItem"></param>
        /// <returns>
        /// Unsuccessful FoodItemResponse if food item does not exist;
        /// Unsuccessful FoodItemResponse if there was an issue updating the food item in the database;
        /// Successful FoodItemResponse with the food item
        /// </returns>
        public async Task <FoodItemResponse> UpdateFoodItemAsync(int id, FoodItem foodItem)
        {
            // check if the food item exists
            var existingFoodItem = await _foodItemRepository.GetAsync(id);

            if (existingFoodItem == null)
            {
                return(new FoodItemResponse($"Food item {id} not found"));
            }

            // remove the old calories from the total calories
            existingFoodItem.DiaryEntry.TotalCalories -= existingFoodItem.Calories;
            // add the new calories to the total calories
            existingFoodItem.DiaryEntry.TotalCalories += foodItem.Calories;

            // update the name and calories of the old food item
            existingFoodItem.Name     = foodItem.Name;
            existingFoodItem.Calories = foodItem.Calories;

            // save the changes
            try
            {
                _foodItemRepository.Update(existingFoodItem);
                await _unitOfWork.CompleteAsync();
            }
            catch (Exception e)
            {
                return(new FoodItemResponse($"An error occurred when updating food item {id}: {e}"));
            }

            return(new FoodItemResponse(existingFoodItem));
        }