/// <summary> /// Updates a course that already exists /// Note that this edits a Course, not a CourseTemplate. /// Only start and end date are editable /// </summary> /// <param name="courseID">The ID of the course to edit</param> /// <param name="updateCourse">a course with the information to edit</param> /// <returns></returns> public CourseDetailsDTO UpdateCourse(int courseID, UpdateCourseViewModel updateCourse) { // Get the course, throw exception if the course is not found Entities.Course course = _db.Courses.SingleOrDefault(x => x.ID == courseID); if (course == null) { throw new CourseNotFoundException(); } // Check if the course tamplate exists var courseTemplate = _db.CourseTemplates.SingleOrDefault(x => x.ID == course.TemplateID); if (courseTemplate == null) { throw new TemplateCourseNotFoundException(); } // Update the start and end date based on the view model course.StartDate = updateCourse.StartDate; course.EndDate = updateCourse.EndDate; course.MaxStudents = updateCourse.MaxStudents; // If all is successfull, we save our changes _db.SaveChanges(); return new CourseDetailsDTO { ID = course.ID, TemplateID = courseTemplate.TemplateID, Name = courseTemplate.Name, Description = courseTemplate.Description, Semester = course.Semester, StartDate = updateCourse.StartDate, EndDate = updateCourse.EndDate, StudentCount = _db.StudentEnrollment.Count(x => x.CourseID == course.ID && x.IsActive == true && x.IsOnWaitingList == false), Students = (from sr in _db.StudentEnrollment join s in _db.Students on sr.StudentID equals s.ID where sr.CourseID == course.ID && sr.IsActive == true && sr.IsOnWaitingList == false select new StudentDTO { SSN = s.SSN, Name = s.Name }).ToList() }; }
public IHttpActionResult UpdateCourse(int id, UpdateCourseViewModel editedCourse) { if (!ModelState.IsValid || editedCourse.StartDate.Equals(DateTime.MinValue) || editedCourse.EndDate.Equals(DateTime.MinValue)) { throw new HttpResponseException(HttpStatusCode.PreconditionFailed); } try { CourseDetailsDTO course = _service.UpdateCourse(id, editedCourse); var location = Url.Link("GetCourse", new { id = course.ID }); return Created(location, course); } catch (CourseNotFoundException) { throw new HttpResponseException(HttpStatusCode.NotFound); } }