tags:

views:

301

answers:

3

If a table has the adjacency model applied (ID,ParentID) how can the heirarchy be returned in Subsonic 3?

+1  A: 

I use this all the time. Just read all the rows. It's what you do with the rows later that matters. I feed them into a DevExpress tree control that automatically picks apart the ID and ParentID to show the tree. Or with a few lines of recursion you can traverse the tree and do anything you like.

var result = from p in _db.Products select p;

P a u l
+2  A: 

All classes are partials, so create a new partial for your class (let's say it' Category) and create child collection (call it SubCategories). Then when you load your object into memory you can load the subcollection:

var allCategories=Categories.All().ToList();
allCategories.ForEach(x=>x.SubCategories=allCategories.Where(y=>y.CategoryID==x.ParentID));

That's freehanded, but that's the idea.

Rob Conery
Any ideas on my question outlined in my post above?
Jon
Like I mention - create a separate class and access the "structured" bits through a separate method - maybe something like "GetItemHierarchy" for instance instead of calling the SubSonic core method.
Rob Conery
Even if I create a method called GetItemHeirarchy, I am still going to just put the code above inside it. Whats the problem with using the core All() method as I need to return all records to populate the Children collection?
Jon
The method on your model should only return the data - you should use another method to output it without the HTML markup.
Rob Conery
Will add a GetItemHeirarchy in the Model and then create a HTMLHelper which will call Model.GetItemHeirarchy and then I'll loop over heirarchy and output the HTML.
Jon
A: 

This is what I have thanks to Rob but I wonder whether the recursive function is still needed? Is there a LINQ alternative?

        var allCategories = Table_1.All().ToList();
        allCategories.ForEach(x => x.Children = allCategories.Where(y => y.ParentID == x.ID));

        var topLevel = allCategories.Where(f => f.ParentID == 0);

        s.AppendLine("<ul>");
        DoStuff(topLevel);
        s.AppendLine("</ul>");

        private void DoStuff(IEnumerable<Table_1> toplevel)
        {
           foreach (var lve in toplevel)
           {
            s.AppendLine("<li>"+lve.Title);
            if (lve.Children.Count() > 0)
            {
                s.AppendLine("<ul>");
                DoStuff(lve.Children);
                s.AppendLine("</ul>");
            }
            s.AppendLine("</li>");
            }
        }
Jon
I'd suggest creating a new question for this, you'll probably get more answers
Adam
You *can* do this in SQL Server if you want to use a function or SP:http://blog.wekeroad.com/blog/Cursed-Recursiveness-Querying-a-Recursive-Join/
Rob Conery
I'll stick with my solution I think
Jon