Example #1
0
 public CourseAssistant MapCourseAssistantDTO(CourseAssistantDTO courseAssistant)
 {
     return(new CourseAssistant {
         CourseId = courseAssistant.CourseId,
         AssistantId = courseAssistant.Assistant.Id
     });
 }
        public async Task <ActionResult <CourseAssistantDTO> > PostCourseAssistant(Guid courseId, CourseAssistantDTO assistant)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            if (courseId != assistant.CourseId)
            {
                ModelState.AddModelError(string.Empty, "The courseId request parameter did not match the courseId property in the data.");
                return(BadRequest(ModelState));
            }

            var cAssistant = courseMapper.MapCourseAssistantDTO(assistant);

            var existingAssistant = await _context.CourseAssistants.FindAsync(cAssistant.CourseId, cAssistant.AssistantId);

            if (existingAssistant != null)
            {
                ModelState.AddModelError(string.Empty, "The assistent you are trying to add already exists.");
                return(BadRequest(ModelState));
            }

            var course = await _context.Courses
                         .Include(c => c.Professor)
                         .Include(c => c.CourseInfo)
                         .FirstOrDefaultAsync(c => c.Id == cAssistant.CourseId);

            var authorization = await authorizationService.AuthorizeAsync(User, course, AuthorizationConstants.CanEditCourseAssistantsPolicy);

            if (!authorization.Succeeded)
            {
                return(Forbid());
            }

            _context.CourseAssistants.Add(cAssistant);
            await _context.SaveChangesAsync();

            cAssistant = await _context.CourseAssistants
                         .Include(ca => ca.Assistant)
                         .FirstOrDefaultAsync(ca => ca.CourseId == cAssistant.CourseId && ca.AssistantId == cAssistant.AssistantId);

            await cache.ClearCourseCacheAsync(courseId, course.CourseInfo.Slug);

            return(CreatedAtAction("GetCourse", new { id = cAssistant.CourseId }, courseMapper.MapCourseAssistant(cAssistant)));
        }