public async Task <QuizQuestion> GetNextQuizQuestionFromTemplateAsync(BiblePathsCoreDbContext context, string bibleId) { QuizQuestion ReturnQuestion = new QuizQuestion(); PredefinedQuiz Template = new PredefinedQuiz(); try { Template = await context.PredefinedQuizzes.Include(T => T.PredefinedQuizQuestions).Where(T => T.Id == PredefinedQuiz).FirstAsync(); } catch { // This is the couldn't find template scenario, ReturnQuestion.QuestionSelected = false; return(ReturnQuestion); } // Ok we've got our Template now which Book/Chapter do we want. int QuestionNumber = QuestionsAsked + 1; int TemplateQuestionNumber = QuestionNumber; // We need to calculate a Template Number if (QuestionNumber > Template.NumQuestions) { TemplateQuestionNumber = QuestionNumber % Template.NumQuestions; if (TemplateQuestionNumber == 0) { TemplateQuestionNumber = Template.NumQuestions; } } // It is actually OK to not find a Question Object, we just treat that as the random book scenario. PredefinedQuizQuestion TemplateQuestion = new PredefinedQuizQuestion(); try { TemplateQuestion = Template.PredefinedQuizQuestions.Where(Q => Q.QuestionNumber == TemplateQuestionNumber).First(); } catch { // This is the more common pick a random Book Scenario. if (Template.BookNumber >= Bible.MinBookListID) { // This is the BookList Scenario return(await GetNextQuizQuestionFromBookListAsync(context, bibleId, Template.BookNumber)); } else { // this is the Book scenario. return(await GetNextQuizQuestionFromBookAsync(context, bibleId, Template.BookNumber)); } } if (TemplateQuestion.BookNumber == 0) { // This is the pick a random Book Scenario, we're unlikely to hit this, more often the question object won't exist at all. if (Template.BookNumber >= Bible.MinBookListID) { // This is the BookList Scenario return(await GetNextQuizQuestionFromBookListAsync(context, bibleId, Template.BookNumber)); } else { // this is the Book scenario. return(await GetNextQuizQuestionFromBookAsync(context, bibleId, Template.BookNumber)); } } else { // This would be the selected Book Scenario, but do we have a selected Chapter? if (TemplateQuestion.Chapter == 0) { // this is the selected book but random Chapter scenario return(await GetNextQuizQuestionFromBookAsync(context, bibleId, TemplateQuestion.BookNumber)); } else { // this is the selected Book and Chapter scenario return(await GetNextQuizQuestionFromBookAndChapterAsync(context, bibleId, TemplateQuestion.BookNumber, TemplateQuestion.Chapter)); } } }