Example #1
0
        public Operation <PlaylistModel> CreatePlaylist(PlaylistModel model)
        {
            // 1. create a playlist if it doesn't already exist,
            // 2. create the tracks if they don't exist
            // 3. add tracks to playlisttracks

            var operation = Operation.Create(() =>
            {
                // 1. create a playlist if it doesn't already exist,
                var playlist = (from plist in _db.Playlists where plist.Name == model.Name select plist).FirstOrDefault();
                if (playlist != null)
                {
                    throw new Exception(string.Format("A playlist named {0} already exists", model.Name));
                }

                var newPlaylist = model.Create();
                _db.Playlists.Add(newPlaylist);

                // 2. create the tracks if they don't exist TODO: requires enhancement
                var newTracks = model.Tracks.Select(t => t.Create()).ToList();
                _db.Tracks.AddRange(newTracks);

                // persist changes to database
                _db.SaveChanges();

                // 3. add tracks to playlisttracks
                var playlistTracks = newTracks.Select(t =>
                {
                    var playlistTrack = new PlaylistTrack()
                    {
                        PlaylistID = newPlaylist.PlaylistID,
                        TrackID    = t.TrackID
                    };

                    return(playlistTrack);
                }).ToList();
                _db.PlaylistTracks.AddRange(playlistTracks);

                // persist changes to database
                _db.SaveChanges();

                // assign id of newly created playlist to the model
                model.PlaylistID = newPlaylist.PlaylistID;
                model.Tracks     = newTracks.Select(t => { return(new TrackModel(t)); }).ToList();

                return(model);
            });

            return(operation);
        }