R – SubSonic and Tree table structure

subsonictree

I have to store a tree-like structure (think folders, for instance) in my database. The model I chose is pretty simple: the table has a FolderId (PK, int, identity), some random attributes and a nullable ParentId (same-table-FK to FolderId, int, nullable).

It all works great and all. I'm using SubSonic's ActiveRecord template. Is there any way to be able to have my generated Folder class have Parent / Children attributes, instead of simply, "Folders"?

I suspect I have to edit the template, probably ActiveRecord.tt. If so, could someone point me to a starting point? Maybe someone has done something similar?

Best Answer

I guess it was too late to see the obvious: I can simply do something along the lines of

partial class Folder
{
    public Folder Parent
    {
        get {
            if (_ParentId.HasValue)
            {
                var repo = ACME.Folder.GetRepo();
                return
                    (from items in repo.GetAll()
                     where _ParentId.Value == items._FolderId
                     select items).First();
            }
            else 
                return null;
        }
    }

    public IQueryable<Folder> Children
    {
        get {
            var repo = ACME.Folder.GetRepo();
            return from items in repo.GetAll()
                   where _FolderId == items.ParentId
                   select items;
        }
    }
}
Related Topic