路由数据获取及封装方法

数据库设计

自联表

定义tree字段

C# 复制代码
    public class LabelValue
    {
        public int label { get; set; }
        public string? value { get; set; }
        public List<LabelValue> children { get; set; }
    }

获取路由方法

C# 复制代码
public Response<object> getMenuList()
{
    Response<object> result = new Response<object>();
    //一级菜单
    List<Menu> Menu_level1_list = db.Queryable<Menu>().Where(t => t.parent_id == 0).ToList();
    List<LabelValue> LabelValueList1 = new List<LabelValue>();
    foreach (var menu1 in Menu_level1_list)
    {
        var labelValue1 = new LabelValue
        {
            label = menu1.ID,
            value = menu1.Name,
            children = BuildMenuTree(menu1.ID)
        };
        LabelValueList1.Add(labelValue1);
    }
    result.Data = LabelValueList1;
    return result;
}

路由递归函数

C# 复制代码
 public List<LabelValue> BuildMenuTree(int? parentId = null)
 {
     SqlSugarClient db = SqlsugarSetup.db;
     var menuList = db.Queryable<Menu>().Where(t => t.parent_id == parentId).ToList();
     var labelValueList = new List<LabelValue>();
     foreach (var menu in menuList)
     {
         var labelValue = new LabelValue
         {
             label = menu.ID,
             value = menu.Name,
             children = BuildMenuTree(menu.ID) 
         };
         labelValueList.Add(labelValue);
     }
     return labelValueList;
 }