public IHttpActionResult Post(Band band) //POST http://localhost:49677/api/artists , values in body { if (!ModelState.IsValid) return BadRequest(ModelState); else { using (var context = new Context()) { context.Bands.Add(band); context.SaveChanges(); } return Created("api/artists/" + band.Id, band); } }
public IHttpActionResult Put(int id, [FromBody] Band updateValues) //PUT http://localhost:49677/api/artists/id , update values in body { if (!ModelState.IsValid) return BadRequest(ModelState); else { Band band; using (var context = new Context()) { band = context.Bands.Where(b => b.Id == id).FirstOrDefault(); } if (band != null) { band.Name = updateValues.Name; //does updates in disconnnected state band.Rating = updateValues.Rating; using (var context = new Context()) //open new context, save update { context.Bands.Attach(band); context.Entry(band).State = EntityState.Modified; context.SaveChanges(); } return Ok(); } else return NotFound(); } }
public IHttpActionResult Delete(int id) //DELETE http://localhost:49677/api/artists/id { Band band; using (var context = new Context()) { band = context.Bands.Where(b => b.Id == id).FirstOrDefault(); context.Bands.Remove(band); context.SaveChanges(); } /*julie lerman showed using a second context and using this code using (var context = new BandEntities()) { context.Bands.Attach(band); context.Entry(band).State = EntityState.Deleted; context.SaveChanges(); */ return Ok(); }