如何在SQL Server中创建递归关联,并在C#中使用实体框架进行循环

本文关键字:实体 框架 循环 并在 SQL Server 创建 关联 递归 | 更新日期: 2023-09-27 17:58:58

我正试图为一个提问者设计一个数据库结构,然后设计一个可以显示该提问者的应用程序。

在我的数据库中,我有一个名为Category的实体表。每个类别可以有多个子类别,每个子类别都可以有多个子类别等。这是一个递归关联。

目前我已经设计如下:

[Table: Category]
category_id
category_number
category_name
parrent_id
[Table: Question]
question_id
question_number
question_wording
question_category

一个具体的例子是:

- Categories
category_id = 1
category_number = 1
category_name = Milk Products
parret_id = null
category_id = 2
category_number = 1.1
category_name = Cheese
parent_id = 1
category_id = 3
category_number = 1.1.1
category_name = Soft
parrent_id = 2
- Questions
question_id = 1
question_number = 1
question_wording = "From 1-5, how much do you like soft cheese?"
category_id = 3
question_id = 2
question_number = 1
question_wording = "How much do you like cheese?"
category_id = 2

我该如何循环浏览类别并显示每个类别和问题,如下所示:

Questionnarie
- Milk products
-- Cheese
-- "How much do you like cheese?"
--- Soft-Cheese
--- "From 1-5, how much do you like soft cheese?"

我正在使用实体框架将我的数据库加载到c#中

提前感谢!

如何在SQL Server中创建递归关联,并在C#中使用实体框架进行循环

您可以像处理普通C#代码一样执行此操作。您可以进行递归函数调用:

public IEnumerable<Category> GetSubCategoriesFor(int catId)
{
    var subs = db.Categories.Where(c => c.ParentId == catId);
    foreach (var sub in subs)
    {
        yield return sub;
        // Recursive call
        foreach (var subsub in GetSubCategoriesFor(sub.Id))
        {
            yield return subsub;
        }
    }
}