1、整体数据量不大的场景

参照:EntityFramework Linq 查询数据获得树形结构-YES开发框架网 (yesdotnet.com)

核心方法GetChildData,特点将所有的数据查到内存中,利用递归去组装树状结构,优点就是只需查一次,但是把所有数据加到内存里,只适合数据量不大的场景

public List<TreeData> GetTreeData(string rowID)
{
    var data = entities.data_ArchiveCategoryGroup
        .Where(w => w.RowID != rowID)
        .Select(s => new TreeData()
        {
            RowID = s.RowID,
            ParentRowID = s.ParentRowID,
            GroupName = s.GroupName,
            Sort = s.Sort
        }).ToList();

    List<TreeData> result = new List<TreeData>();
    foreach (var p in data.Where(w => w.ParentRowID == "").OrderBy(o => o.Sort))
    {
        result.Add(new TreeData()
        {
            RowID = p.RowID,
            ParentRowID = p.ParentRowID,
            GroupName = p.GroupName,
            Sort = p.Sort,
            Childs = GetChildData(data, p.RowID)
        });
    }
    return result;
}

public List<TreeData> GetChildData(List<TreeData> dataList, string id)
{
    List<TreeData> nodeList = new List<TreeData>();
    var children = dataList.Where(t => t.ParentRowID == id);
    foreach (var o in children)
    {
        o.Childs = GetChildData(dataList, o.RowID);
        nodeList.Add(o);
    }
    if (nodeList.Count == 0)
        return null;
    else
        return nodeList;
}

public class TreeData
{
    public string RowID { get; set; }

    public string ParentRowID { get; set; }

    public string GroupName { get; set; }
    public int Sort { get; set; }
    public List<TreeData> Childs { get; set; }
}

2、树状结构的统一封装结果查询

参照:

Tree Structure in EF Core: How to configure a self-referencing table and use it / Habr

Tree Structure in EF Core: How to configure a self-referencing table and use it (itnan.ru)

ef 更新数据库表结构_EF Core中的树结构:如何配置和使用自引用表_cullen2012的博客-CSDN博客