Storing folder hierarchy in relational database

|▌冷眼眸甩不掉的悲伤 提交于 2019-12-19 08:01:07

问题


I have objects representing folders and I'm wondering if they should be represented in the database.

On the one hand it seems like the easiest way would be to not represent folder objects and just store a path value for objects contained in a folder. Problems I see with this is that you can't persist an folder whose descendants do not contain any items, which isn't too big of a deal. Also I don't have a clear idea of how to load the folder hierarchy to display (such as in a TreeView) without loading everything into memory upfront, which would probably be a performance issue.

The alternative is to have a "Folder" table with references to its parent folder. This seems like it should work, but I'm unsure how to allow folders with the same name as long as they do not share a parent. Should that even be something the DB should be concerning itself with or is that something that I should just enforce in the the business logic?


回答1:


The idea is something like this (self-referencing):

CREATE TABLE FileSystemObject ( 
    ID int not null primary key identity,
    Name varchar(100) not null,
    ParentID int null references FileSystemObject(ID),
    constraint uk_Path UNIQUE (Name, ParentID),
    IsFolder bit not null
)



回答2:


Take a look at the ERD in the middle of this page. Factoring out the hierarchy into a separate table permits you to support multiple taxonomies.




回答3:


First ask yourself what the purpose is of keeping the hierarchy in the database and what functionality you gain by that. Then ask consider the work and maintenance that goes into doing it.

If you're simply using it to fill a tree control, there are built-in controls that go directly against the folder system. Would that work better for you? Do you gain something beyond that by storing it in the database? How do you plan to keep the database in sync with the actual folder system, which can be changed outside of the DB? Unless your providing a virtual file system it may be better to just go directly against the real thing with relevant paths stored in the database.




回答4:


SQL Server has a hierarchyid data type that has support for hierarchical structures. Works only in the full version, mind you.



来源:https://stackoverflow.com/questions/719278/storing-folder-hierarchy-in-relational-database

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!