//public Operation<PlaylistTrackModel> CreatePlaylistTrack(PlaylistTrackModel model) //{ // var operation = Operation.Create(() => // { // if (model.PlaylistID == 0) // { // // create a new playlist first before creating a playlist track // } // var playlistTrack = (from plistTrack in _db.PlaylistTracks where plistTrack.PlaylistID == model.PlaylistID && plistTrack.TrackID == model.TrackID select plistTrack).FirstOrDefault(); // if (playlistTrack != null) throw new Exception("This track is already in your playlist"); // var newPlaylistTrack = model.Create(); // _db.PlaylistTracks.Add(newPlaylistTrack); // // persist changes to database // _db.SaveChanges(); // // assign id of newly created playlistTrack to the model // model.PlaylistTrackID = newPlaylistTrack.PlaylistTrackID; // return model; // }); // return operation; //} #endregion #region Update Operations public Operation <PlaylistModel> UpdatePlaylist(PlaylistModel model) { var operation = Operation.Create(() => { var playlist = (from plist in _db.Playlists where plist.PlaylistID == model.PlaylistID select plist).Include("PlaylistTracks.Track").FirstOrDefault(); if (playlist == null) { throw new Exception("Playlist not found"); } model.Update(playlist); // create any new tracks if they don't exist //TODO: requires enhancement var newTracks = new List <Track>(); model.Tracks.ForEach(t => { // if track id is 0 then it must be a new track if (t.TrackID == 0) { newTracks.Add(t.Create()); } }); // only add if tehre are any tracks if (newTracks.Count > 0) { _db.Tracks.AddRange(newTracks); } // update any changes to existing tracks var tracks = playlist.PlaylistTracks.Select(plistTrack => { return(plistTrack.Track); }).ToList(); tracks.ForEach(track => { var trackModel = model.Tracks.Where(trackM => trackM.TrackID == track.TrackID).FirstOrDefault(); if (trackModel != null) { trackModel.Update(track); } }); // persist changes to database _db.SaveChanges(); // add newly added tracks to playlisttracks var playlistTracks = newTracks.Select(t => { var playlistTrack = new PlaylistTrack() { PlaylistID = playlist.PlaylistID, TrackID = t.TrackID }; return(playlistTrack); }).ToList(); _db.PlaylistTracks.AddRange(playlistTracks); // persist changes to database _db.SaveChanges(); // get all tracks afresh var allTracks = (from plist in _db.PlaylistTracks where plist.PlaylistID == model.PlaylistID join track in _db.Tracks on plist.TrackID equals track.TrackID select track).ToList(); // project out trackmodel model.Tracks = allTracks.Select(t => { return(new TrackModel(t)); }).ToList(); return(model); }); return(operation); }