I have the same situation. I was not able to solve it directly with LINQ / EF. Instead, I decided to create a database view using recursive generic table expressions, as described here . I created a user-defined function that intersects all parents with a child (or vice versa), and then a view that uses this user-defined function, which I imported into my EF object context.
(disclaimer: simplified code, I really have not tested this)
I have two tables, for example MyTable (containing all the elements) and MyParentChildTable containing the relations ChildId, ParentId
Then I defined the following udf:
CREATE FUNCTION dbo.fn_getsupertree(@childid AS INT) RETURNS @TREE TABLE ( ChildId INT NOT NULL ,ParentId INT NULL ,Level INT NOT NULL ) AS BEGIN WITH Parent_Tree(ChildId, ParentId) AS (
and the following view:
CREATE VIEW VwSuperTree AS ( SELECT tree.* FROM MyTable CROSS APPLY fn_getsupertree(MyTable.Id) as tree ) GO
This gives me for each child all parents with their "tree level" (direct parent has level 1, parent parent has level 2, etc.). From this point of view, it is easy to request the item with the highest level. I just imported the view into my EF context to be able to query it using LINQ.
source share