private async Task <bool> UpdatePlaylistSongs(string[] selectedSongs, PlaylistModel playlistModel) { try { //Gets connections from the db including the playlists and the songs inside. var connections = await _context.PlaylistSongsConnections .Include(connection => connection.Playlist).Include(connection => connection.Song).ToListAsync(); //Getting all connections of the given playlist. var playlistSongs = (from connection in connections where connection.Playlist != null && connection.Playlist.ID == playlistModel.ID select connection.Song.ID).ToList(); // For performance we use HashSet of the selected songs from the edit view of the playlist var selectedSongsHS = new HashSet <string>(selectedSongs); // Iterate all songs in the DB foreach (var song in _context.Songs) { // Check if the current song from DB is selected by the view if (selectedSongsHS.Contains(song.ID.ToString())) { // Assign the song to the playlist, if the playlist isn't assigned yet if (!playlistSongs.Contains(song.ID)) { var connection = new PlaylistSongModel() { Playlist = playlistModel, Song = song }; _context.PlaylistSongsConnections.Add(connection); } } else { // If we are here than the song is not selected, and if the playlist currently assigned to this song // we should than unassign the playlist and update the song DB if (playlistSongs.Contains(song.ID)) { var connectionToDelete = connections.FirstOrDefault(connection => connection.Song.ID == song.ID); _context.PlaylistSongsConnections.Remove(connectionToDelete); } } } } catch (Exception) { return(false); } return(true); }
private async Task <bool> CreatingPlaylistConnections(string[] selectedSongs, PlaylistModel playlist) { try { // For performance we use HashSet of the selected songs from the edit view of the playlist. var selectedSongsHS = new HashSet <string>(selectedSongs); var songsConnections = new List <PlaylistSongModel>(); // The current songs of the playlist. // var playlistSongs = new HashSet<int>(playlist.Playlist.Select(s => s.ID)); // Iterate all songs in the DB. foreach (var song in _context.Songs) { // Check if the current song from DB is selected by the view. if (selectedSongsHS.Contains(song.ID.ToString())) { //Creating a connection. var connection = new PlaylistSongModel() { Playlist = playlist, Song = song }; //Add it to the local list. songsConnections.Add(connection); } } //Saving the new collection in the db. await _context.PlaylistSongsConnections.AddRangeAsync(songsConnections); await _context.SaveChangesAsync(); } catch (Exception) { return(false); } return(true); }