How can I model this class in a database?

后端 未结 4 1621
猫巷女王i
猫巷女王i 2020-12-12 02:33

I need a little of help. This is my design to organize several categories.

   Category 1
     Sub Category 1.1
       Sub Category 1.1.1
     Sub Category 1.         


        
4条回答
  •  Happy的楠姐
    2020-12-12 03:26

    For this, you can have a table where an item can reference its parent, if any.

    enter image description here

    If the ParentId column is NULL, the category is a root one. If not, the parent is referenced.

    You can then find the subcategories of a category by walking through the table and searching for items with ParentId equal to Id of the category.

    Note that ParentId must be indexed for better performance, and that there must be a foreign key of ParentId to Id to ensure the validity of your data.

    Storing recursively the categories:

    private void SaveCategoryRecursively(Category category)
    {
        foreach (var subCategory in category.SubCategories)
        {
            query(@"
    insert into [dbo].[Categories] ([Id], [ParentId], ...)
    values (@id, @parentId, ...)", ...);
            this.SaveCategoryRecursively(subCategory);
        }
    }
    
    public void SaveCategories(IEnumerable rootCategories)
    {
        foreach (var category in rootCategories)
        {
            query(@"
    insert into [dbo].[Categories] ([Id], [ParentId], ...)
    values (@id, NULL, ...)", ...);
            this.SaveCategoryRecursively(category);
        }
    }
    

提交回复
热议问题