Reputation: 5083
I have two tables in SQL:
DOCUMENT
ID int
Description varchar(50)
DOCUMENTLINK
ParentID int
ChildID int
How do I return the hierarchy (only two levels are used) formed by these two tables as an object using LINQ?
The structure would be something like:
Parent1
---------Child1
---------Child2
Parent2
---------Child3
Parent3
Parent4
---------Child2
---------Child3
Parent5
---------Child1
---------Child4
---------Child5
Upvotes: 0
Views: 104
Reputation: 2416
LINQ answer:
var tree = from top in nodes
from middle in nodes
from bottom in nodes
where top.Id == middle.ParentId
&& middle.Id == bottom.Id
select new
{
Top = top,
Middle = middle,
Bottom = bottom
};
Upvotes: 2
Reputation: 2416
The SQL answer is:
SELECT *
FROM (Table1
INNER JOIN Table1 AS Table1_1 ON Table1.ParentID = Table1_1.ID)
INNER JOIN Table1 AS Table1_2 ON Table1_1.ParentID = Table1_2.ID;
Note, this will only show items that have all levels. To get childless parents included, change all the inner joins to left outer joins
Upvotes: 1