Question

Ok so I have been trying to figure out how to embed multiple select's in a LINQ query and have been failing being that I don't use LINQ all that often.

I have come up with a fairly straight forward simple SQL statement I am trying to convert and I would appreciate it if anyone can help convert this to LINQ and explain the logic there.

SELECT * FROM TABLE_A
WHERE TABLE_B_REF IN
(SELECT TABLE_B_REF FROM TABLE_B
WHERE TABLE_B.TABLE_C_REF IN 
(SELECT TABLE_C_REF FROM TABLE_C WHERE C_NUMBER = '10001'))

I have googled around but what I am getting is too complex to follow for multiple embedded queries.

Was it helpful?

Solution

A SQL join seems much simpler here. Assuming you've set up navigation properties correctly, that would look a bit like this:

from a in db.TableA
where a.TableB.TableC.C_Number == "10001"
select a;

Or in fluent syntax:

db.TableA.Where(a => a.TableB.TableC.C_Number == "10001")

The corresponding SQL would be something like this:

SELECT a.* 
FROM TABLE_A a
JOIN TABLE_B b ON a.TABLE_B_REF = b.TABLE_B_REF
JOIN TABLE_C c ON b.TABLE_C_REF = c.TABLE_C_REF
WHERE c.C_NUMBER = '10001'
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top