简体   繁体   中英

Can I have a where clause that works on a grandchild in a LINQ query?

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();

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