// PUT api/Artists/5 public HttpResponseMessage PutArtist(int id, Artist artist) { if (!ModelState.IsValid) { return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ModelState); } var artistToUpdate = db.Artists.FirstOrDefault(a => a.ArtistId == id); if (artistToUpdate != null && artist != null) { artistToUpdate.UpdateWith(artist); } else { return Request.CreateResponse(HttpStatusCode.BadRequest); } db.Entry(artistToUpdate).State = EntityState.Modified; try { db.SaveChanges(); } catch (DbUpdateConcurrencyException ex) { return Request.CreateErrorResponse(HttpStatusCode.NotFound, ex); } return Request.CreateResponse(HttpStatusCode.OK); }
public void UpdateWith(Artist artist) { if (!string.IsNullOrWhiteSpace(artist.ArtistName)) { this.ArtistName = artist.ArtistName; } if (!string.IsNullOrWhiteSpace(artist.Country)) { this.Country = artist.Country; } if (artist.DateOfBirth.HasValue) { this.DateOfBirth = artist.DateOfBirth; } }
// POST api/Artists public HttpResponseMessage PostArtist(ArtistDto artist) { if (ModelState.IsValid) { var newArtist = new Artist { ArtistName = artist.ArtistName, Country = artist.Country, DateOfBirth = artist.DateOfBirth }; db.Artists.Add(newArtist); db.SaveChanges(); HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.Created, newArtist); response.Headers.Location = new Uri(Url.Link("DefaultApi", new { id = newArtist.ArtistId })); return response; } else { return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ModelState); } }
// POST api/Artists public HttpResponseMessage PostArtist(Artist artist) { if (ModelState.IsValid) { db.Artists.Add(artist); db.SaveChanges(); HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.Created, artist); response.Headers.Location = new Uri(Url.Link("DefaultApi", new { id = artist.ArtistId })); return response; } else { return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ModelState); } }