private void UpdateMovieMovies(string[] selectedMovies, Rental rentalToUpdate) { if (selectedMovies == null) { rentalToUpdate.MovieAssigns = new List <MovieAssign>(); return; } var selectedMovieHS = new HashSet <string>(selectedMovies); var rentalMovies = new HashSet <int> (rentalToUpdate.MovieAssigns.Select(c => c.Movie.MovieID)); foreach (var movie in _context.Movies) { if (selectedMovieHS.Contains(movie.MovieID.ToString())) { if (!rentalMovies.Contains(movie.MovieID)) { rentalToUpdate.MovieAssigns.Add(new MovieAssign { RentalID = rentalToUpdate.RentalID, MovieID = movie.MovieID }); } } else { if (rentalMovies.Contains(movie.MovieID)) { MovieAssign movieToRemove = rentalToUpdate.MovieAssigns.FirstOrDefault(i => i.MovieID == movie.MovieID); _context.Remove(movieToRemove); } } } }
public async Task <IActionResult> Create([Bind("RentalID,Cpf,RentalDate")] Rental rental, string[] selectedMovies) { if (selectedMovies != null) { rental.MovieAssigns = new List <MovieAssign>(); foreach (var movie in selectedMovies) { var movieToAdd = new MovieAssign { RentalID = rental.RentalID, MovieID = int.Parse(movie) }; rental.MovieAssigns.Add(movieToAdd); } } if (ModelState.IsValid) { _context.Add(rental); await _context.SaveChangesAsync(); return(RedirectToAction(nameof(Index))); } PopulateAssignedMovieData(rental); return(View(rental)); }