简体   繁体   English

Linq到具有多级子引用的实体查询

[英]Linq to entities query having multi level child references

I have been having too much trouble designing a query to retrieve questions that a candidate have already attempted and another query for the questions that a candidate has not attempted. 我在设计查询以检索候选人已经尝试过的问题以及另一个针对候选人尚未尝试过的问题的查询时遇到了太多麻烦。 This is for a examination/test/form/survey type application. 这是用于检查/测试/表格/调查类型的应用程序。

架构图

The scenario is a candidate(OAS_UserDetail) is associated with many groups(OAS_Group). 该方案是候选项(OAS_UserDetail)与许多组(OAS_Group)相关联。 One group can have many tests. 一组可以进行许多测试。 A test can have many questions. 测试可能有很多问题。 A question can have many options. 一个问题可以有很多选择。

When a candidate attempts a question it is stored in table TestResponse having reference to the session, (the answerSelected in table TestResponse is actually the QuestionOption.Id). 当候选人尝试提问时,该问题将存储在表TestResponse中并引用了会话(表TestResponse中的answerSelected实际上是QuestionOption.Id)。 I believe TestSession can act as a bridge for TestResponse to get the details of user, test and group. 我相信TestSession可以充当TestResponse的桥梁,以获取用户,测试和组的详细信息。

This seems to me a good but somewhat complex design for me as far as querying is concerned through Linq. 就我而言,对于通过Linq进行查询而言,这对我来说是一个不错的设计,但有些复杂。 Below is what I tried to do and got stuck and end up writing Linq in method syntax instead of query syntax. 下面是我试图做的,被卡住了,最终用方法语法而不是查询语法编写了Linq。

OAS.DataModels.OAS_Question questionsAttempted = 
            from q in db.OAS_Questions
            where q.OAS_Test.OAS_Group.Candidates.Contains(
                      db.OAS_UserDetails.Single(u => u.UserName == HttpContext.User.Identity.Name)
            )                         
            select q;

Linq query syntax is very similar to SQL. Linq查询语法与SQL非常相似。 You should be able to do what you need using "join" operators. 您应该能够使用“ join”运算符执行所需的操作。

Here's a good overview: 这是一个很好的概述:

http://code.msdn.microsoft.com/101-LINQ-Samples-3fb9811b http://code.msdn.microsoft.com/101-LINQ-Samples-3fb9811b

So you are looking for questions of a candidate of which the options either are or aren't in the candidate's TestResponse records. 因此,您正在寻找候选人的TestResponse记录中选项是否存在的TestResponse I think this could work: 我认为这可能有效:

(from u in OAS_UserDetail
from g in u.OAS_Group
from t in g.OAS_Test
from q in t.OAS_Question
from o in q.OAS_QuestionOption
where u.Id == userId // a variable
where u.OAS_TestSession
      .SelectMany(s => s.OAS_TestResponse)
      .Select(r => r.AnswerSelectedId).Contains(o.Id)
select q).Distinct()

and for the questions that the candidate did not attempt: where !u.OAS_TestSession... 对于候选人未尝试的问题: where !u.OAS_TestSession...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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