【问题标题】:Can I have a where clause that works on a grandchild in a LINQ query?我可以有一个在 LINQ 查询中作用于孙子的 where 子句吗?
【发布时间】:2014-03-25 20:11:51
【问题描述】:

我有三个表,每个表都有一个主键和外键,例如 TestId 和 UserTestId 等。

Exam > Test > UserTest

据我了解,我可以使用 LINQ 从这些数据中获取数据,如下所示:

        var exams = _examsRepository
       .GetAll()
       .Where(q => q.SubjectId == subjectId)
       .Include(q => q.Tests.Select(t => t.UserTests))
       .ToList();

这将选择所有考试,考试的测试和 SubjectId == subjectID 的测试的 UserTests

是否有任何可能的方法可以进一步限制这一点,以便仅显示 UserTests 的 UserId 为 123 时的数据?

如果答案是否定的,那么我是否应该重写此 LINQ 以首先转到 _userTestsRepository,然后朝另一个方向向上而不是向下工作?

【问题讨论】:

  • 你可以在这里使用子查询
  • Cris - 你能举个例子吗?我确实尝试了答案,但运行时出现错误。
  • 我无法确定,您使用的是哪个框架?这是 EF,如果是,是哪个版本?
  • @Chris Ballard - 抱歉,我没有提供足够的信息。我们正在使用 EF6 和 SQL Server 2012。

标签: c# linq


【解决方案1】:

this question 中,他们提供了一种解决方案,可以满足您的需求,但在我看来,这有点像黑客。
或者,您可以放弃包含语句并进行手动连接,您可以根据需要在子表上应用尽可能多的过滤器。
可能看起来像这样:

var data = (from ex in context.exams
           join t in context.tests on ex.Id equals test.ExamID
           join ut in context.userTests on t.Id equals ut.TestId
           where ut.UserId = 123
           select new {ex, ut}).ToList();

【讨论】:

    猜你喜欢
    • 2012-08-09
    • 2014-05-07
    • 1970-01-01
    • 1970-01-01
    • 2020-12-31
    • 1970-01-01
    • 1970-01-01
    • 2022-01-21
    • 2018-08-14
    相关资源
    最近更新 更多