Accepted answer

i think the best i'm going to get is to load the entire hierarchy in one hit from the structure i want the top parent of:

var structurequery = from item in context.structures
                         .include(x => x.parent)
                     where item.structureid == structureid
                     select item;

then just use the code:

while (structure.parent != null)
    structure = structure.parent;


you can use the linq take construct, for instance

            var first3customers = (
                from c in customers
                select new {c.customerid, c.customername} )


i like the question and can't think of a linq-y way of doing this. but could you perhaps implement this on your repository class? after all, there should be only one at the top and if the need for it is there, then maybe it deserves a structurerepository.getroot() or something.


i have a similar situation. i didn't manage to solve it directly with linq/ef. instead i solved by creating a database view using recursive common table expressions, as outlined here. i made a user-defined function that cross applies all parents to a child (or vice versa), then a view that makes use of this user-defined function which i imported into my ef object context.

(disclaimer: simplified code, i didn't actually test this)

i have two tables, say mytable (containing all items) and myparentchildtable containing the childid,parentid relation

i have then 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
  with parent_tree(childid, parentid)
    -- anchor member (am)
    select childid, parentid, 0
    from myparentchildtable
    where childid = @childid

    union all

    -- recursive member (rm)
    select info.childid, info.parentid, tree.[level]+1
    from myparentchildtable as info
      join parent_tree as tree
        on info.childid = tree.parentid
  insert into @tree
    select * from parent_tree;


and the following view:

create view vwsupertree as (
select tree.*
from mytable
cross apply fn_getsupertree( as tree

this gives me for each child, all parents with their 'tree level' (direct parent has level 1, parent of parent has level 2, etc.). from that view, it's easy to query the item with the highest level. i just imported the view in my ef context to be able to query it with linq.


this is not a direct answer, but the problem you are having is related to the way you are storing your tree. there are a couple ways of simplifying this query by structuring data differently.

one is to use a nested set hierarchy, which can simplify many kinds of queries across trees.

another is to store a denomralized table of ancestor/descendant/depth tuples. this query then becomes finding the tuple with the current structure as the descendant with the maximum depth.

Related Query

More Query from same tag