// PUT api/Artist/5 public HttpResponseMessage PutArtist(int id, Artist artist) { if (!ModelState.IsValid) { return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ModelState); } if (id != artist.ArtistId) { return Request.CreateResponse(HttpStatusCode.BadRequest); } db.Entry(artist).State = EntityState.Modified; try { db.SaveChanges(); } catch (DbUpdateConcurrencyException ex) { return Request.CreateErrorResponse(HttpStatusCode.NotFound, ex); } return Request.CreateResponse(HttpStatusCode.OK); }
// PUT api/Artists/5 public HttpResponseMessage PutArtist(int id, Artist artist) { Artist dbArtist = DataMapper.CreateOrLoadArtist(repository, artist); artist.Update(dbArtist); repository.Update(id, dbArtist); return Request.CreateResponse(HttpStatusCode.OK); }
public static void EditArtist(int id, Artist artist) { artist.ArtistId = id; HttpResponseMessage response = client.PutAsXmlAsync("api/artists/" + id, artist).Result; if (response.IsSuccessStatusCode) { Console.WriteLine("Artist with id: {0} edited!", id); } else { Console.WriteLine("{0} ({1})", (int)response.StatusCode, response.ReasonPhrase); } }
public void Update(Artist artist) { if (this.Name != null) { artist.Name = this.Name; } if (this.Country != null) { artist.Country = this.Country; } if (this.DateOfBirth != null) { artist.DateOfBirth = this.DateOfBirth; } }
// POST api/Artist 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); } }
public static Artist CreateOrLoadArtist(IRepository<Artist> repository, Artist entity) { Artist artist = repository.Get(entity.ArtistId); if (artist != null) { return artist; } Artist newArtist = repository.Add(new Artist() { Name = entity.Name, Country = entity.Country, DateOfBirth = entity.DateOfBirth, Songs = entity.Songs, Albums = entity.Albums }); return newArtist; }
public static void AddArtist(string name, string country, DateTime dateOfBirth) { Artist newArtist = new Artist { Name = name, Country = country, DateOfBirth = dateOfBirth }; var content = new FormUrlEncodedContent(new[] { new KeyValuePair<string, string>("name", name), new KeyValuePair<string, string>("country", country), new KeyValuePair<string, string>("DateOfBirth", dateOfBirth.ToShortDateString()), }); HttpResponseMessage response = client.PostAsync("api/artist", content).Result; if (response.IsSuccessStatusCode) { Console.WriteLine("Artist added: {0}", newArtist.Name); } else { Console.WriteLine("{0} ({1})", (int)response.StatusCode, response.ReasonPhrase); } }