给梦一个奔跑的方向!
PDF Print E-mail
User Rating: / 1
PoorBest 
Written by xlingfairy
Sunday, 23 August 2009 00:46
有Category表,如下结构:
CREATE TABLE QV_Category(
 ID INT IDENTITY(1,1) NOT NULL,
 ParentID INT NOT NULL DEFAULT 0,
 CategoryName NVARCHAR(30) NOT NULL,
 IsLeaf BIT NOT NULL DEFAULT 1, 
 CreatedOn DATETIME DEFAULT GETDATE(),
 CreatedBy NVARCHAR(30),
 ModifiedOn DATETIME,
 ModifiedBy NVARCHAR(30),
 
 CONSTRAINT QV_Category_PK PRIMARY KEY (ID),
 CONSTRAINT QV_Category_UK UNIQUE (ParentID,CategoryName)
);
 
 
ParentID 即本表里,以存在的ID
要以树的方式取出这个表(层次关系),只能用递归。
现在,我用LINQ给它实现一把,也是递归。
        private XElement GetCategoryTree(int parentID) {
            XElement node = new XElement("l" ,
 
                from cat in dc.QV_Category
                let id = cat.ID
                where cat.ParentID == parentID
                select GetCategoryTree(id) ,
 
                from cat in dc.QV_Category
                where cat.ID == parentID
                select new XAttribute[] { new XAttribute("Name" , cat.CategoryName) , new XAttribute("IsLeaf" , cat.IsLeaf) , new XAttribute("ID" , cat.ID) }
                );
            return node;
        }
 
调用:
XElement node = GetCategoryTree(0);
 
 
生成结果如:
<l>
  <l Name="电影" IsLeaf="false" ID="1">
    <l Name="动作" IsLeaf="true" ID="3" />
  </l>
  <l Name="娱乐" IsLeaf="false" ID="2" />
</l>
Last Updated ( Sunday, 23 August 2009 00:58 )
 

Add comment


Security code
Refresh

Popular Contents

Recommend

Site Info

Members : 1
Content : 130
Web Links : 7
Content View Hits : 99646

Links