public async Task<IHttpActionResult> PutStudent(int id, Student student) { if (!ModelState.IsValid) { return BadRequest(ModelState); } if (id != student.Id) { return BadRequest(); } var dbStudent = db.Students.FirstOrDefault(o => o.Id == student.Id); var once = true; foreach (var course in student.Courses) { var s = db.Courses.FirstOrDefault(o => o.Id == course.Id); if (once) { dbStudent.Courses.Clear(); once = false; } dbStudent.Courses.Add(s); } dbStudent.Name = student.Name; dbStudent.Year = student.Year; dbStudent.Gender = student.Gender; dbStudent.Age = student.Age; db.Entry(dbStudent).State = EntityState.Modified; try { await db.SaveChangesAsync(); } catch (DbUpdateConcurrencyException) { if (!StudentExists(id)) { return NotFound(); } else { throw; } } return StatusCode(HttpStatusCode.NoContent); }
public async Task<IHttpActionResult> PostStudent(Student student) { if (!ModelState.IsValid) { return BadRequest(ModelState); } db.Students.Add(student); await db.SaveChangesAsync(); return CreatedAtRoute("DefaultApi", new { id = student.Id }, student); }