コード例 #1
0
        /// <summary>
        /// Import a list of students into database
        /// </summary>
        /// <param name="requestModel"></param>
        /// <returns></returns>
        public async Task <List <ImportStudentResponse> > ImportStudent(List <ImportStudentRequest> requestModel)
        {
            //check if request is empty
            if (!requestModel.Any())
            {
                throw new HttpStatusCodeException(HttpStatusCode.NotFound, "StudentService: request is empty");
            }

            //Check records in requestModel for duplicate email
            CheckImportStudentRecords(requestModel);

            var students = new List <Student>();

            //Get all email form database
            var listOfEmail = _repoWrapper.User.FindAllAsync().Result.Select(u => u.Email).ToList();

            foreach (var s in requestModel)
            {
                //Check if Email already existed
                if (listOfEmail.Contains(s.Email))
                {
                    //clear pending changes
                    _repoWrapper.DeleteChanges();
                    throw new HttpStatusCodeException(HttpStatusCode.NotFound,
                                                      "StudentService: Email: " + s.Email + " Already Existed");
                }

                var defaultEvaluationPoint = (await _paramService.FindById(GlobalParams.ParamDefaultEvaluationPoint))?.Value ?? GlobalParams.DefaultEvaluationPoint;

                //Add student to pending changes
                students.Add(_repoWrapper.Student.CreateWithoutSave(ImportStudentRequest.NewStudentFromRequest(s, defaultEvaluationPoint)));
            }

            try
            {
                //Create all students at once
                await _repoWrapper.Save();
            }
            catch (Exception)
            {
                //clear pending changes if fail
                _repoWrapper.DeleteChanges();
                throw new HttpStatusCodeException(HttpStatusCode.InternalServerError,
                                                  "StudentService: Could not create new student");
            }

            return(students.Select(ImportStudentResponse.CreateFromStudent).ToList());
        }