Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

I am writing a small bookmarking tool in ASP.NET MVC, and each bookmark is stored in a folder. 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?

share|improve this question
    
You can use hierarchyid introduced by SQL Server 2008. –  Bogdan Sahlean Jun 1 at 16:44
add comment

1 Answer

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. 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. 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:

share|improve this answer
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.