// PUT api/Albums/5 public HttpResponseMessage PutAlbum(int id, Album album) { if (!ModelState.IsValid) { return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ModelState); } var albumToUpdate = db.Albums.FirstOrDefault(a => a.AlbumId == id); if (albumToUpdate != null && album != null) { albumToUpdate.UpdateWith(album); } else { return Request.CreateResponse(HttpStatusCode.BadRequest); } db.Entry(albumToUpdate).State = EntityState.Modified; try { db.SaveChanges(); } catch (DbUpdateConcurrencyException ex) { return Request.CreateErrorResponse(HttpStatusCode.NotFound, ex); } return Request.CreateResponse(HttpStatusCode.OK); }
public void UpdateWith(Album album) { if (!string.IsNullOrWhiteSpace(album.AlbumTitle)) { this.AlbumTitle = album.AlbumTitle; } if (album.AlbumYear.HasValue) { this.AlbumYear = album.AlbumYear; } if (!string.IsNullOrWhiteSpace(album.Producer)) { this.Producer = album.Producer; } }
// POST api/Albums public HttpResponseMessage PostAlbum(string artistName, [FromBody]AlbumDto album) { if (string.IsNullOrWhiteSpace(artistName)) { 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); } if (artist.Albums.Any(a => a.AlbumTitle == album.AlbumTitle)) { return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ModelState); } if (ModelState.IsValid) { var newAlbum = new Album { AlbumTitle = album.AlbumTitle, AlbumYear = album.AlbumYear, Producer = album.Producer }; db.Albums.Add(newAlbum); artist.Albums.Add(newAlbum); db.SaveChanges(); HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.Created, newAlbum); response.Headers.Location = new Uri(Url.Link("DefaultApi", new { id = newAlbum.AlbumId })); return response; } else { return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ModelState); } }