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
2009-06-08 16:44:01
+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
2009-06-08 18:15:00
Any ideas on my question outlined in my post above?
Jon
2009-06-09 13:16:53
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
2009-06-09 19:08:50
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
2009-06-09 20:03:47
The method on your model should only return the data - you should use another method to output it without the HTML markup.
Rob Conery
2009-06-10 19:02:27
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
2009-06-11 08:44:19
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
2009-06-09 11:16:51
I'd suggest creating a new question for this, you'll probably get more answers
Adam
2009-06-10 10:02:09
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
2009-06-10 19:01:26