コード例 #1
0
        public IHttpActionResult Get(int id) //GET http://localhost:49677/api/artists/id
        {
            Band band;

            using (var context = new Context()) 
            {
                band = context.Bands.Find(id);  //Where(b => b.Id == id).FirstOrDefault();
                context.Entry(band).Collection(a => a.Albums).Load(); //explicit load. i have disabled lazy loading
            }

            if (band == null)
                return NotFound();
            else
                return Ok(band);
        }
コード例 #2
0
        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();
            }
        }