简体   繁体   English

在关系数据库中存储文件夹层次结构

[英]Storing folder hierarchy in relational database

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. 此外,我还没有清楚地知道如何加载文件夹层次结构以显示(例如在TreeView中)而不将所有内容加载到内存中,这可能是性能问题。

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? 这甚至应该是DB应该关注的事情,还是我应该在业务逻辑中执行的事情?

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
)

Take a look at the ERD in the middle of this page . 请查看本页中间的ERD。 Factoring out the hierarchy into a separate table permits you to support multiple taxonomies. 将层次结构分解为单独的表允许您支持多个分类法。

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. 除非您提供虚拟文件系统,否则最好直接使用存储在数据库中的相关路径来对抗真实事物。

SQL Server has a hierarchyid data type that has support for hierarchical structures. SQL Server具有支持层次结构的hierarchyid数据类型。 Works only in the full version, mind you. 请注意,仅适用于完整版。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM