// PUT api/Songs/5 public HttpResponseMessage PutSong(int id, Song song) { if (!ModelState.IsValid) { return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ModelState); } var songToUpdate = db.Songs.FirstOrDefault(s => s.SongId == id); if (songToUpdate != null && song != null) { songToUpdate.UpdateWith(song); } else { return Request.CreateResponse(HttpStatusCode.BadRequest); } db.Entry(songToUpdate).State = EntityState.Modified; try { db.SaveChanges(); } catch (DbUpdateConcurrencyException ex) { return Request.CreateErrorResponse(HttpStatusCode.NotFound, ex); } return Request.CreateResponse(HttpStatusCode.OK); }
public void UpdateWith(Song song) { if (!string.IsNullOrWhiteSpace(song.SongTitle)) { this.SongTitle = song.SongTitle; } if (song.SongYear.HasValue) { this.SongYear = song.SongYear; } if (!string.IsNullOrWhiteSpace(song.Genre)) { this.Genre = song.Genre; } }
// POST api/Songs public HttpResponseMessage PostSong(string artistName, string albumTitle, [FromBody]SongDto song) { if (string.IsNullOrWhiteSpace(artistName) || string.IsNullOrWhiteSpace(albumTitle)) { return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ModelState); } var artist = db.Artists.Include(a => a.Albums).SingleOrDefault(a => a.ArtistName == artistName); if (artist == null) { return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ModelState); } var album = artist.Albums.SingleOrDefault(a => a.AlbumTitle == albumTitle); if (album == null) { return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ModelState); } if (album.Songs.Any(s => s.SongTitle == song.SongTitle)) { return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ModelState); } if (ModelState.IsValid) { var newSong = new Song { SongTitle = song.SongTitle, SongYear = song.SongYear, Genre = song.Genre, Artist = artist, Album = album }; db.Songs.Add(newSong); db.SaveChanges(); HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.Created, newSong); response.Headers.Location = new Uri(Url.Link("DefaultApi", new { id = newSong.SongId })); return response; } else { return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ModelState); } }