public async Task <Meal> EditMealAsync(EditMealInputModel inputModel) { var currentMeal = await this.mealsRepository .All() .FirstOrDefaultAsync(x => x.Id == inputModel.Id); currentMeal.Name = inputModel.Name; if (inputModel.NewImageFile != null) { currentMeal.PictureUrl = await this.cloudinaryService.UploudAsync(inputModel.NewImageFile); } currentMeal.Type = inputModel.Type; currentMeal.CaloriesPer100Grams = inputModel.CaloriesPer100Grams; foreach (var foodPreference in this.mealsPreferencesRepository .All() .Where(x => x.MealId == currentMeal.Id)) { this.mealsPreferencesRepository.Delete(foodPreference); } await this.mealsPreferencesRepository.SaveChangesAsync(); if (inputModel.FoodPreferences != null) { foreach (var foodPreference in inputModel.FoodPreferences) { FoodPreference currentPreference; currentPreference = await this.foodPreferenceRepository .All() .FirstAsync(x => x.Preference == foodPreference); MealPreference mealPreference = new MealPreference { Meal = currentMeal, MealId = currentMeal.Id, Preference = currentPreference, PreferenceId = currentPreference.Id, }; await this.mealsPreferencesRepository.AddAsync(mealPreference); currentMeal.FoodPreferences.ToList().Add(mealPreference); currentPreference.Meals.ToList().Add(mealPreference); } await this.mealsRepository.SaveChangesAsync(); } return(currentMeal); }
public async Task <IActionResult> Edit(EditMealInputModel inputModel) { if (!this.cloudinaryService.IsFileValid(inputModel.NewImageFile) || !this.ModelState.IsValid) { if (!this.cloudinaryService.IsFileValid(inputModel.NewImageFile)) { this.ModelState.AddModelError("PictureFile", "Plese enter valid file format!"); } return(this.View(inputModel)); } var meal = await this.mealsService.EditMealAsync(inputModel); return(this.Redirect($"/Trainers/Meals/Details/{meal.Id}")); }