我可以在LINQ查询中的孙子项上使用where子句吗? [英] Can I have a where clause that works on a grandchild in a LINQ query?
问题描述
我有三个表,每个表都与一个主键和外键(如TestId和UserTestId等)连接.
I have three tables that are each connected with a primary key and foreign key such as TestId and UserTestId etc.
Exam > Test > UserTest
据我了解,我可以使用LINQ从这些数据中获取数据,如下所示:
It's my understanding I can use LINQ to get the data from these like this:
var exams = _examsRepository
.GetAll()
.Where(q => q.SubjectId == subjectId)
.Include(q => q.Tests.Select(t => t.UserTests))
.ToList();
这将选择所有考试,针对考试的考试和针对其中SubjectId == subjectID的那些考试的UserTest
This will select all the exams, Tests for the exams and UserTests for those Tests where SubjectId == subjectID
有什么办法可以进一步限制它,使其仅在UserTests的UserId为123时显示数据?
Is there any possible way I could further limit this so that it only showed the data for when the UserTests had a UserId of 123?
如果答案是否定的,那么我应该重写此LINQ,以便首先转到_userTestsRepository,然后朝另一个方向(而不是向下)工作吗?
If the answer is no then should I rewrite this LINQ to first go to the _userTestsRepository and then work in the other direction up instead of down?
推荐答案
在此问题中他们提供了可以满足您需求的解决方案,但我认为这有点像hack.
或者,您可以退出include语句并进行手动联接,可以按照需要在子表上应用尽可能多的过滤器.
可能看起来像这样:
In this question they offer a solution which does what you want but in my opinion feels a little like a hack.
Alternatively you could step away from include statements and do a manual join, you can apply as many filters on sub tables as you like that way.
Could look a lil like this :
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();
这篇关于我可以在LINQ查询中的孙子项上使用where子句吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!