用递归实现无限级菜单,产品分类,盖楼式评论、留言等功能。
下列代码不能直接使用
CREATE TABLE [dbo].[P_Category](
[Code] [varchar](36) NOT NULL PRIMARY KEY,
[Parent_Code] [varchar](36) NULL,
[Depth] [int] NULL,
[Name] [varchar](50) NULL
)
GO
INSERT [dbo].[P_Category] ([Code], [Parent_Code], [Depth], [Name]) VALUES (N'101', N'1', 2, N'木门')
INSERT [dbo].[P_Category] ([Code], [Parent_Code], [Depth], [Name]) VALUES (N'10101', N'101', 3, N'室内木门')
INSERT [dbo].[P_Category] ([Code], [Parent_Code], [Depth], [Name]) VALUES (N'1010101', N'10101', 4, N'A02')
INSERT [dbo].[P_Category] ([Code], [Parent_Code], [Depth], [Name]) VALUES (N'101010101', N'10101', 5, N'A01')
INSERT [dbo].[P_Category] ([Code], [Parent_Code], [Depth], [Name]) VALUES (N'10101010101', N'101010101', 6, N'A0101')
INSERT [dbo].[P_Category] ([Code], [Parent_Code], [Depth], [Name]) VALUES (N'102', N'1', 2, N'B')
INSERT [dbo].[P_Category] ([Code], [Parent_Code], [Depth], [Name]) VALUES (N'10201', N'102', 3, N'B1')
INSERT [dbo].[P_Category] ([Code], [Parent_Code], [Depth], [Name]) VALUES (N'1020101', N'10201', 4, N'B2')
private List CategoryCacheAllList { get; set; }
[Route("")]
public HttpResponseMessage Get()
{
var list = CacheHelper>.GetCache(CategoryAllListCacheKEY);
if (list == null)
{
CategoryCacheAllList = CategoryService.GetCacheList(); //取得数据库里面所有数据
list = new List();
CategoryJson(list, "1");
CacheHelper>.SetCache(CategoryAllListCacheKEY, list);
}
return Request.CreateResponse(HttpStatusCode.OK, list);
//下面的代码这个没试
//string json = JsonConvert.SerializeObject(categoryList, Formatting.Indented);
//return json;
}
///
/// 取得兄弟节点
///
///
///
public void CategoryJson(List categoryList, string parentCode)
{
var list = CategoryCacheAllList.FindAll(p => p.ParentCode == parentCode);
if (list.Count > 0)
{
foreach (var item in list)
{
CategoryTreeJson(item, item.Code);
categoryList.Add(item);
}
}
}
///
/// 递归出子对象
///
///
///
private void CategoryTreeJson(Category sbCategory, string parentCode)
{
var list = CategoryCacheAllList.FindAll(p => p.ParentCode == parentCode);
if (list.Count > 0)
{
sbCategory.Children = new List();
foreach (var item in list)
{
CategoryTreeJson(item, item.Code);
sbCategory.Children.Add(item);
}
}
}
namespaceVipSoft.Base.Core.Entity
{///
///产品分类///
[Table("VipSoft_Category")]public classCategory
{///
///编码///
[Column(ColumnType.IncrementPrimary, Name = "Code")]public string Code { get; set; }///
///父级编码///
[Column(Name = "Parent_Code")]public string ParentCode { get; set; }///
///深度///
[Column(Name = "Depth")]public int? Depth { get; set; }///
///分类名称///
[Column(Name = "Name")]public string Name { get; set; }///
///排序///
[Column(Name = "Sequence")]public int? Sequence { get; set; }///
///状态///
[Column(Name = "Status")]public int? Status { get; set; }///
///创建时间///
[Column(Name = "Create_Date")]public DateTime? CreateDate { get; set; }public List Children { get; set; }
}
}