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
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
};
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
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.