/// <summary> /// Updates the course with the given ID, if a course /// with the given ID was not found then null an object not /// found exception is thrown. /// </summary> /// <returns></returns> public CourseDTO UpdateCourse(int ID, UpdateCourseViewModel course) { // 1. Validate // 2. Update var courseEntity = _db.Courses.SingleOrDefault(x => x.ID == ID); if(courseEntity == null) { throw new CourseNotFoundException(); } courseEntity.StartDate = course.StartDate; courseEntity.EndDate = course.EndDate; _db.SaveChanges(); // 3. Building the return value var courseTemplate = _db.CourseTemplates.SingleOrDefault(x => x.CourseID == courseEntity.CourseID); if (courseTemplate == null) { throw new ApplicationException("Something went horribly wrong"); } var studentCount = _db.CourseRegistrations.Count(x => x.CourseID == courseEntity.ID); var returnValue = new CourseDTO { ID = courseEntity.ID, CourseID = courseEntity.CourseID, StartDate = courseEntity.StartDate, EndDate = courseEntity.EndDate, Name = courseTemplate.Name, StudentCount = studentCount }; return returnValue; }
public IHttpActionResult UpdateCourse(int id, UpdateCourseViewModel newCourse) { if (ModelState.IsValid) { try { _service.UpdateCourse(id, newCourse); return Ok(); } catch (CourseNotFoundException) { throw new HttpResponseException(HttpStatusCode.NotFound); } } else { return StatusCode(HttpStatusCode.PreconditionFailed); } }