public IActionResult AddCourse(CourseModel courseModel) { if (!ModelState.IsValid) { return(View(courseModel)); } Subject subject = subjectRepository.FindByName(courseModel.SubjectName); if (subject == null) { subject = new Subject(); subject.Name = courseModel.SubjectName; subject = subjectRepository.Create(subject); } Course course = new Course(); course.Name = courseModel.Name; course.Description = courseModel.Description; course.AuthorId = BitConverter.ToInt32(HttpContext.Session.Get("userId")); Author author = authorRepository.Read(course.AuthorId); course.SubjectId = subject.Id; course.Author = author; if (subject.Courses == null) { subject.Courses = new List <Course>(); } subject.Courses.Add(course); if (author.Courses == null) { author.Courses = new List <Course>(); } author.Courses.Add(course); courseRepository.Create(course); return(RedirectToAction("Courses", "Course")); }