如何在SQL Server中创建递归关联并使用Entity Framework在C#中循环遍历?

问题描述

| 我正在尝试为一个questionnarie设计一个数据库结构,然后为一个可以显示该questionnarie的应用程序设计。 在我的数据库中,我有一个名为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#中 提前致谢!     

解决方法

        您将执行与普通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;
        }
    }
}