1

I am working in an ASP.NET project with EF and I have some trouble with finding a correct query. I need to work without lazy-loading.

I have following data structure: A Module contains pages. A Page contains PageItems. A PageItem contains an Item. An Item can contains other Items.

Leaving out the recursive aspect of Items containing Items at first, I need a query to feed the structure of a single module into a treeview.

What I want is :

  • The Module with the given ID
    • Including all pages
      • Including all PageItems
        • Including all Items with ParentItem_ID == 0
          • Including all ChildItems

I started with this:

return base._entities.Modules
            .Include(m => m.Paginas
                .Select(p => p.PaginaItems
                    .Select(pi => pi.Item)
                    .Select(i => i.ChildItems)))
            .Where(m => m.Module_ID == id)
            .FirstOrDefault();

This query works, but it ignores the item-hierarchy and displays all items as direct child of a page. What would actually need is something like this:

return base._entities.Modules
           .Include(m => m.Paginas
               .Select(p => p.PaginaItems
                   .Select(pi => pi.Item)
                   .Where(i => i.I_ParentItem_ID == 0)
                   .Select(i => i.ChildItems)))
           .Where(m => m.Module_ID == id)
           .FirstOrDefault();

But it does not work.

I an relatively new to LINQ, and any help would really be appreciated.

1
  • In this case you should use explicit joins. Commented Apr 26, 2012 at 12:23

1 Answer 1

2

As you need a condition in a nested collection you should use join, like:

(from mod in c.Modules
join pag in c.Paginas on mod.Module_Id equals pag.Module_Id
join pi in c.PaginaItems on pag.Pagina_Id equals pi.Pagina_Id
join item in c.Items.Where(i => i.I_ParentItem_ID == 0) on pi.PaginaItem_Id
    equals item.PaginaItem_Id
join ci in c.ChildItems on item.I_ParentItem_ID equals ci.I_ParentItem_ID
select mod).FirstOrDefault()

I abbreviated base._entities to c (for context) and made some assumptions about Id names and possibly overlooked the odd syntax error, but this should be a good start.

Sign up to request clarification or add additional context in comments.

1 Comment

WOW that was really helpful. Now I've got it. Although I had to alter the query a bit: instead of select mod I had to write select new{mod,pag,pi,item} and then return qry.mod, otherwise the navigation properties of Module were null.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.