'How to perform a LEFT JOIN on the same table using Linq?
Consider a table where rows may be linked to each other. We need to select the rows that meet a certain requirement, OR where its linked row meets that requirement, using Linq.
For the sake of simplicity, consider the following table:
ID | Linked_ID | Active |
---|---|---|
1 | null | 0 |
2 | 1 | 1 |
3 | null | 1 |
4 | 3 | 0 |
...and we'd like to have all rows where either its own Active or its linked row's Active equals 1.
The following SQL statement...
SELECT t1.*
FROM MyTable t1
LEFT JOIN MyTable t2
ON t1.Linked_ID = t2.ID
WHERE t1.Active = 1 OR t2.Active = 1
...gives the desired results:
ID | Linked_ID | Active |
---|---|---|
2 | 1 | 1 |
3 | null | 1 |
4 | 3 | 0 |
But how can this be expressed in Linq?
Similar questions on Stack Overflow concern either two different tables, or don't need Linq. It starts with something like this, but after hours of fiddling, I still haven't figured it out. I prefer using Linq methods, but if I get an answer in a Linq query syntax - I'd be happy to get it resolved either way.
var joined = dbSet.GroupJoin(dbSet, t => t.ID, t => t.Linked_ID, (t1, t2) => new { t1, t2 });
var result = joined.SelectMany(???
Solution 1:[1]
Can you try this (I have no way to execute this so it need to be proven)
from t1 in MyTable
where t1.Active = 1 OR t2.Active = 1
where t1.Linked_ID == t1.MyTable.ID
select t1
Following these instructions https://newbedev.com/linqpad-convert-sql-to-linq-command
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Pimenta |