[英]Representing paths in SQL Server database (ASP.NET MVC)
I am writing a small bookmarking tool in ASP.NET MVC, and each bookmark is stored in a folder. 我正在ASP.NET MVC中编写一个小型书签工具,每个书签都存储在一个文件夹中。 I am currently representing this by simply storing a path as a string in the database, but when it comes to beginning to display items by folder and list folders this seems like an efficient way to do it.
我目前通过简单地将路径作为字符串存储在数据库中来表示这一点,但是当开始按文件夹和列表文件夹显示项目时,这似乎是一种有效的方法。
Is there any built-in way to represent and then manipulate paths in a database? 有没有内置的方式来表示然后操纵数据库中的路径? Or an accepted best practice?
还是公认的最佳实践?
If you are talking paths like in filesystem paths, then you might want to start thinking about about a trees and a hierachical system. 如果您正在谈论诸如文件系统路径之类的路径,那么您可能要开始考虑一棵树和一个层次系统。
In essence, you will have an additional table in a form named like Category or something, which is self referencing with a ParentId
. 本质上,您将具有一个名为Category或类似名称的形式的附加表,该表可以使用
ParentId
自引用。 With this you can iterate along your caegories until, there is no parent or child item, depending on the direction of your query and build a path with the result of your query. 借助此方法,您可以遍历大类,直到没有父项或子项,这取决于查询的方向,并使用查询的结果构建路径。 This of course can get ugly, if your bookmarkings have more then 1 category.
如果您的书签的类别超过1个,那么这当然会很难看。 You will want to get some additional validation into this.
您将需要对此进行一些其他验证。
The following code is acutally from an article on the web, which I used myself, but I can't find the article again, to quote it as the source. 以下代码是我自己用过的一篇网上文章的摘要,但我再次找不到该文章,将其引用为源。
public class Category
{
public int CategoryId { get; set; }
public string Name { get; set; }
public int? ParentId { get; set; }
public virtual Category Parent { get; set; }
public virtual ICollection<Category> Children { get; set; }
}
public class CategoryMapping : EntityTypeConfiguration<Category>
{
public CategoryMapping()
{
HasKey(x => x.CategoryId);
Property(x => x.CategoryId).HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);
Property(x => x.Name)
.IsRequired()
.HasMaxLength(255);
//Parent is optional, because root node has no parent
HasOptional(x => x.Parent)
.WithMany(x => x.Children)
.HasForeignKey(x => x.ParentId)
.WillCascadeOnDelete(false);
}
}
References: 参考文献:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.