问题描述
我有三个表,每个表都有一个主键和一个外键,例如 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,然后朝另一个方向向上而不是向下工作?
在这个问题 他们提供的解决方案可以满足您的需求,但在我看来,这有点像 hack.
或者,您可以放弃包含语句并进行手动连接,您可以根据需要在子表上应用尽可能多的过滤器.
可能看起来像这样:
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();
问题描述
I have three tables that are each connected with a primary key and foreign key such as TestId and UserTestId etc.
Exam > Test > UserTest
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();
This will select all the exams, Tests for the exams and UserTests for those Tests where SubjectId == subjectID
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?
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?
推荐答案
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();