public IActionResult UpdateCourseForAuthor(Guid authorId, Guid courseId, CourseForUpateDto course) //changed to IAction due to we are allowing to insert { if (!_courseLibraryRepository.AuthorExists(authorId)) { return(NotFound()); } var courseForAuthorFromRepo = _courseLibraryRepository.GetCourse(authorId, courseId); //changing implementation to support also inserts if (courseForAuthorFromRepo == null) { var courseToAdd = _mapper.Map <Entities.Course>(course); courseToAdd.Id = courseId; _courseLibraryRepository.AddCourse(authorId, courseToAdd); _courseLibraryRepository.Save(); var courseToReturn = _mapper.Map <CourseDto>(courseToAdd); return(CreatedAtRoute("GetCourseForAuthor", new { authorId, courseId = courseToReturn.Id }, courseToReturn)); } // Map the entity to a CourseForUpdateDto // apply the updated field values to that dto // map the courseForAuthorFromRepo back to an entity _mapper.Map(course, courseForAuthorFromRepo); _courseLibraryRepository.UpdateCourse(courseForAuthorFromRepo); _courseLibraryRepository.Save(); return(NoContent()); }
public ActionResult PartiallyUpdateForAuthor(Guid authorId, Guid courseId, JsonPatchDocument <CourseForUpateDto> patchDocument) { if (!_courseLibraryRepository.AuthorExists(authorId)) { return(NotFound()); } var courseForAuthorFromRepo = _courseLibraryRepository.GetCourse(authorId, courseId); if (courseForAuthorFromRepo == null) { var courseDto = new CourseForUpateDto(); patchDocument.ApplyTo(courseDto, ModelState); if (!TryValidateModel(courseDto)) { return(ValidationProblem(ModelState)); } var courseToAdd = _mapper.Map <Entities.Course>(courseDto); courseToAdd.Id = courseId; _courseLibraryRepository.AddCourse(authorId, courseToAdd); _courseLibraryRepository.Save(); var courseToReturn = _mapper.Map <CourseDto>(courseToAdd); return(CreatedAtRoute("GetCourseForAuthor", new { authorId, courseId = courseToReturn.Id }, courseToReturn)); } var courseToPatch = _mapper.Map <CourseForUpateDto>(courseForAuthorFromRepo); patchDocument.ApplyTo(courseToPatch, ModelState); //Explicit Validation if (TryValidateModel(courseToPatch)) { return(ValidationProblem(ModelState)); } _mapper.Map(courseToPatch, courseForAuthorFromRepo); _courseLibraryRepository.UpdateCourse(courseForAuthorFromRepo); _courseLibraryRepository.Save(); return(NoContent()); }