public IHttpActionResult AddCourse(AddCourseViewModel course) { if (ModelState.IsValid) { try { var result = _service.AddCourse(course); var location = Url.Link("GetCourse", new { id = result.ID }); return Created(location, result); } catch (AppObjectNotFoundException) { return NotFound(); } catch (AppBadRequestException) { return BadRequest(); } } else { return StatusCode(HttpStatusCode.PreconditionFailed); } }
/// <summary> /// Adds a course with a pre existing CourseTemplate to the database, /// If there is no template available an exception is thrown, /// Or if the course object is not valid an exception is thrown /// </summary> /// <param name="course">A course object containing the information to create the new course</param> /// <returns>The course object</returns> public CourseDTO AddCourse(AddCourseViewModel course) { //Check if there is a template for the course var courseTemplate = _db.CourseTemplates.SingleOrDefault(x => x.TemplateID == course.TemplateID); if (courseTemplate == null) { throw new AppObjectNotFoundException(); } //Create a new Course object to add to the database var newCourse = new Course { EndDate = course.EndDate, StartDate = course.StartDate, TemplateID = course.TemplateID, MaxStudents = course.MaxStudents, Semester = course.Semester }; if (newCourse == null) { throw new AppBadRequestException(); } //Add the new course to the database _db.Courses.Add(newCourse); _db.SaveChanges(); // Get the course object for the ID of the returned CourseDTO var courseId = _db.Courses.SingleOrDefault(x => x.ID == newCourse.ID); if (courseId == null) { // If the course is not found, there are inconsistancies // in the database: throw new AppServerErrorException(); } var studentCount = (from cr in _db.CourseRegistrations where courseId.ID == cr.ID where cr.Active select cr.StudentID).ToList().Count(); //Make a new CourseDTO to return to the client var courseDto = new CourseDTO { ID = courseId.ID, StartDate = course.StartDate, EndDate = course.EndDate, Name = courseTemplate.Name, Semester = course.Semester, StudentCount = studentCount }; if (courseDto == null) { throw new AppBadRequestException(); } return courseDto; }