public IHttpActionResult AddTeacherToStudentSubject(string studentId, int subjectId, string teacherId) { Student student = studentsService.GetById(studentId); Teacher teacher = teachersService.GetById(teacherId); if (student == null || teacher == null || subjectsService.GetById(subjectId) == null) { return(NotFound()); } try { if (!student.StudentAttendsSubject.Select(x => x.Subject.SubjectId).Contains(subjectId)) { throw new NullReferenceException("Student doesn't attend this subject!"); } else if (!teacher.TeacherTeachesSubject.Select(x => x.Subject?.SubjectId).Contains(subjectId)) { throw new NullReferenceException("Teacher doesn't teach this subject and therefore cannot be added to this student-subject pair!"); } else { logger.Info("Linking teacher with student-subject"); studentsService.AddTeacherToStudentSubject(studentId, subjectId, teacherId); return(Ok(student.StudentAttendsSubject.Select(x => x.TacherTeachesSubject?.Teacher))); } } catch (NullReferenceException e) { logger.Error(e.Message, "Adding teacher to student-subject pair"); return(ResponseMessage(Request.CreateErrorResponse(HttpStatusCode.BadRequest, e.Message))); } }