将嵌套关系模型转换为字符串

Convert nested relational model to a string

我在 MVC5 entity framework 中有一个数据模型,其中 post 有一个类别。这个分类可以嵌套如.

Top Level: 0
  -> Lower Level: 1
      -> Lowest Level: 2

这在我的模型中表示为:

public class CategoryModel
{
   public int Id { get; set; }
   public CategoryModel ParentCategory { get; set; }

   public string Title { get; set; }
}

现在,当我显示我的 post 时,它具有(来自上面的示例)类别 "Lowest Level 2",我想显示

"Top level: 0 > Lower Level: 1 > Lowest Level: 2"

在该页面上的某个地方通知用户他们在哪里。

问题是我不知道该怎么做。 可能真的很简单(就像 lambda 中的所有东西一样),但我真的不知道怎么做,而且我的谷歌搜索技能真的很差。

根据评论问题编辑: post 定义为:

public class PostModel
{
    public int Id { get; set; }
    public CategoryModel Category { get; set; } // a post can only have one category
    public string Text { get; set; }
}

我想做的是跟随 CategoryModel 关系,然后继续跟随类别 ParentCategory 直到它为空。这始终是一对一的关系。

更多编辑: 我相当简单地可以使用 TSQL-CTE 表达式来做到这一点,但仍然不知道如何将其转换为 lambda。

SQL:

;WITH Hierarchy(Title, CatId, LEVEL, CategoryPath)
AS
(
  Select c.Title, c.Id, 0, c.Title
    FROM Categories c
    WHERE c.[ParentCategory_Id] IS NULL
  UNION ALL
  SELECT c.Title, c.Id, H.LEVEL+1, H.CategoryPath+' > '+c.Title
    FROM Categories c
    INNER JOIN Hierarchy H ON H.CatId = c.[ParentCategory_Id]
)

SELECT SPACE(LEVEL*4) + H.Title, *
FROM Hierarchy H
ORDER BY H.CategoryPath

结果:

假设您有一个 CategoryModel 的实例,您可以编写一个函数来构建一个包含所有标题链的字符串列表:

private void FormatCategories(CategoryModel model, List<string> result)
{
    result.Add(model.Title);
    if (model.ParentCategory != null)
    {
        FormatCategories(model.ParentCategory, result);
    }
}

然后:

CategoryModel model = ... // fetch your model from wherever you are fetching it
var result = new List<string>();
FormatCategories(model, result);

现在剩下的就是颠倒列表中元素的顺序并将它们连接起来以检索最终结果:

result.Reverse();
string formattedCategories = string.Join(" -> ", result);
// At this stage formattedCategories should contain the desired result