public IActionResult DeleteConfirmed(int id) { using (workoutsRepo) { var workout = workoutsRepo.GetById(id); workoutsRepo.Delete(workout); workoutsRepo.SaveChanges(); return(RedirectToAction(nameof(Index))); } }
public async Task <IActionResult> Edit(int id, EditWorkoutViewModel vm) { if (id != vm.WorkoutId) { return(NotFound()); } if (ModelState.IsValid) { try { var user = await userManager.GetUserAsync(HttpContext.User); var exercises = exercisesRepo.All().Where(e => e.ApplicationUserId == user.Id); Workout workout = workoutsRepo.GetById(id); var selectedExercises = vm.Exercises.Select(e => Int32.Parse(e)); workout.WorkoutName = vm.WorkoutName; workout.WorkoutDetails = vm.WorkoutDetails; var filteredExercises = exercises.Where(e => selectedExercises.Contains(e.ExerciseId)).ToList(); var filteredExercisesIds = filteredExercises.Select(fe => fe.ExerciseId).ToList(); workoutsRepo.Update(workout); //get what is in db var oldExercises = weRepo.All().Where(we => we.WorkoutId == id).ToList(); var oldExercisesIds = oldExercises.Select(ce => ce.ExerciseId).ToList(); var oldWE = new WorkoutExercise(); //remove not selected foreach (var eId in oldExercisesIds) { if (!filteredExercisesIds.Contains(eId)) { oldWE = oldExercises.Where(oe => oe.ExerciseId == eId).FirstOrDefault(); weRepo.Delete(oldWE); } } //add selected not in db foreach (var e in filteredExercises) { if (!oldExercisesIds.Contains(e.ExerciseId)) { weRepo.Add(new WorkoutExercise() { Exercise = e, Workout = workout }); } } workoutsRepo.SaveChanges(); weRepo.SaveChanges(); } catch (DbUpdateConcurrencyException) { var exists = workoutsRepo.GetById(id);; if (exists == null) { return(NotFound()); } else { throw; } } finally { workoutsRepo.Dispose(); exercisesRepo.Dispose(); weRepo.Dispose(); userManager.Dispose(); } return(RedirectToAction(nameof(Index))); } return(View(vm)); }