2011-01-20 24 views
0

使用:SQL Server 2008中,WCF 4 REST,EF確定哪些樹節點是樹葉在延遲加載WCF REST API

我有一個表示樹

TABLE Category 
(
    CatId int IDENTITY(1,1) NOT NULL PRIMARY KEY, 
    ParentId int NULL, 
    Name nvarchar(50) NOT NULL 
) 

我是鄰接表的表創建一個WCF REST API以允許客戶端以延遲加載的方式構建樹。做查詢來獲取節點的子節點(nodeid在下面)很簡單。我遇到的是需要確定哪些節點是葉節點。

tree = _context.Categories 
       .Where(c => c.ParentId == nodeid) 
       .Select(p => new TreeNode 
       { 
        id = p.CatId, 
        parentId = p.ParentId ?? -1, // -1 = NULL in data struct 
        name = p.Name, 
        isleaf = true // how to figure this out? 
       }).ToList(); 

任何想法:(我刪除了所有的錯誤處理,從下面的代碼數= 0操作,空處理,等等)?我可以爲這個查詢存儲過程,並且已經考慮過使用CTE,但是我不想通過整個樹進行遞歸 - 只需要獲取指定節點的子節點。

編輯(1月20日,上午10:40) 我已決定更改DB架構以添加「IsLeaf」位列。然後我做了更新以相應地設置IsLeaf - 這意味着我不必在運行時動態地找出它。可能效率更高,但我仍然很好奇我將如何去做。請指教。

回答

1

LINQ(還沒有?)沒有遞歸函數。因此,雖然它有點容易在MSSQL中,LINQ我建議做以下(僞):

// These two lines is one LINQ statement 
level = select all root nodes (ParentID == NULL) 
add level nodes to result 
// C# loop 
while level is not empty 
    // The loop body except for the assignment in the end is one LINQ statement 
    next = select all nodes that have parentId in level 
    for each node in next 
    find parent node 
    add to result with updated parent info 
    // C# assignment 
    level = next 

正如你可以看到它是LINQ和C#的組合。在做完所有這些之前,也可能需要在本地提供表格的內容。

此外,您可能需要更新算法以檢查週期(如有必要)。