简体   繁体   中英

LINQ-EF Query grouping multiple tables

I have a complex query to do with EF by using LINQ. I know the way to do that with multiple loops manually but I would like to do it with LINQ queries:

Scenario: Test center for students

Database involves in my scenario 5 basic tables: tests, questions, answers, results and participants.

Tests contains the tests themselves. (int testId, string testName). 1-N relationship with questions.

Questions contains test questions. (int questionID,int testId,string questionText)

Answers contains every possible answers for a question: (int answerId,int questionId, bool isCorrect) 1-N relationship with Questions.

Results contains a record per every answer, related to the student answering the question: (int ResultId, int AnswerId, int participantId, bool isSelectedByParticipant) 1:1 relationship with Answers.

Participants : (int participantId). 1:1 relationship with Results.

I would like to know how many answers did a student respond successfully per every test (so a student can do some exams of course). A question can have one or more answers correct, but always at least one answer correct, so if every answer related with a question is not marked by the student(isSelectedByParticipant = false) the result for that question is wrong.

在此处输入图片说明

Thanks a lot everyone for ur help.

Something similar to:

 results.GroupBy(r => r.ParticipientId).Select(p => new
                {
                    StudentId = p.Key,
                    Count = p.GroupBy(pr => pr.Answer.QuestionId).Select( cc => new {
// any correct answer is not selected or any incorrect answer is selected
                        notCorrect = cc.Any(q => !q.IsSelected && q.Answer.IsAnswerCorrect) || cc.Any(q => q.IsSelected && !q.Answer.IsAnswerCorrect)
                    }).Count(res => !res.notCorrect)
                });

Here is working example

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM