public async Task <ActionResult <BulkStudentCourseDto[]> > PostBulkStudentCourses(List <BulkStudentCourseDto> bulkStudentCourseDtos) { if (!ModelState.IsValid) { return(BadRequest(ModelState)); } List <StudentCourse> addedStudentCourses = new List <StudentCourse>(); BulkStudentCourseDto bulkDto = new BulkStudentCourseDto(); var validData = bulkStudentCourseDtos.Where(w => w.Username == User.Identity.Name); try { // get valid foreach (var b in validData) { var studentCourse = await _context.StudentCourses // .Select(BulkStudentCourseDto.AsBulkStudentCourseDto) .FirstOrDefaultAsync( x => x.Session.Name == b.Session && x.Semester.Name == b.Semester && x.Course.Code == b.Code && x.Student.MatricNo == b.MatricNo ); if (studentCourse != null) { continue; } studentCourse = new StudentCourse { Score = b.Score }; // get session var session = await _context.Sessions.FirstOrDefaultAsync(f => f.Name == b.Session); if (session != null) { studentCourse.SessionId = session.Id; } else { var entity = new Session { Name = b.Session }; entity.AddTracker(User.Identity.Name); await _context.Sessions.AddAsync(entity); studentCourse.Session = entity; this.RemoveCache(CacheKeys.Session); } // get semester var semester = await _context.Semesters.FirstOrDefaultAsync(f => f.Name == b.Semester); if (semester != null) { studentCourse.SemesterId = semester.Id; } else { var entity = new Semester { Name = b.Semester }; entity.AddTracker(User.Identity.Name); await _context.Semesters.AddAsync(entity); studentCourse.Semester = entity; this.RemoveCache(CacheKeys.Semester); } // get course var course = await _context.Courses.FirstOrDefaultAsync(f => f.Code == b.Code); if (course != null) { studentCourse.CourseId = course.Id; } else { var entity = new Course { Code = b.Code, Title = b.Code, }; entity.AddTracker(User.Identity.Name); await _context.Courses.AddAsync(entity); studentCourse.Course = entity; this.RemoveCache(CacheKeys.Course); } // get student var student = await _context.Students.FirstOrDefaultAsync(f => f.MatricNo == b.MatricNo); if (student != null) { studentCourse.StudentId = student.Id; } else { var entity = new Student { MatricNo = b.MatricNo, Lastname = b.MatricNo, Firstname = b.MatricNo, }; entity.AddTracker(User.Identity.Name); await _context.Students.AddAsync(entity); studentCourse.Student = entity; this.RemoveCache(CacheKeys.Student); } studentCourse.AddTracker(User.Identity.Name); await _context.StudentCourses.AddAsync(studentCourse); int rows = await _context.SaveChangesAsync(); if (rows > 0) { addedStudentCourses.Add(studentCourse); b.Id = studentCourse.Id; } bulkDto.Id = studentCourse.Id; } if (bulkStudentCourseDtos.Any(a => a.Id > 0) == true || addedStudentCourses.Count > 0) { this.RemoveCache(CacheKeys.StudentCourse); } } catch (Exception ex) { return(BadRequest(ex.Message)); } return(bulkStudentCourseDtos.ToArray()); }