2012-06-04 204 views
-2

美好的一天好朋友!目前我正在研究这种名为Modified Pre-Order Tree Traversal(MPTT)的数据库模型设计。在看到使用通用表格表达式(CTE)由于其质量差的缺点,我发现了使用MPTT的建议。但在使用MPTT的好处之前,我需要通过添加'正确'和'左'节点值来重新设计我的数据库表。为此,我需要创建一个程序来自动化和更新表中每个数据的值。我的问题是我不能制作一个能够自动化节点值的程序。我试图将一个PHP语言转换为C#代码,但我无法做到。我在编程方面的一个弱点是创建'递归'方法。在C中自动遍历树遍历#

我使用此链接作为我的参考。 Hierarchical database model

这里就是我想转换到C#

<?php 
function rebuild_tree($parent, $left) { 
    // the right value of this node is the left value + 1 
    $right = $left+1; 

    // get all children of this node 
    $result = mysql_query('SELECT title FROM tree '. 
          'WHERE parent="'.$parent.'";'); 
    while ($row = mysql_fetch_array($result)) { 
     // recursive execution of this function for each 
     // child of this node 
     // $right is the current right value, which is 
     // incremented by the rebuild_tree function 
     $right = rebuild_tree($row['title'], $right); 
    } 

    // we've got the left value, and now that we've processed 
    // the children of this node we also know the right value 
    mysql_query('UPDATE tree SET lft='.$left.', rgt='. 
       $right.' WHERE title="'.$parent.'";'); 

    // return the right value of this node + 1 
    return $right+1; 
} 
?> 
+0

你是什么具体问题? C#和PHP通常很相似,你的代码也不例外。这段代码的转换应该非常简单。 – Enigmativity

回答

0

下面是我自己的代码代码,请让我知道如果有一个更好的解决方案

int right = 0; 

    public int rebuild_tree(int parent, int left) 
    { 
     // the right value of this node is the left value + 1 
     right = left + 1; 

     // get all children of this node 
     command = conn.CreateCommand(); 
     command.CommandText = "SELECT cat_id FROM tbl_RefDataCategory_mst WHERE [email protected]"; 
     command.Parameters.Add("parent", SqlDbType.Int).Value = parent; 

     using (SqlDataReader reader = command.ExecuteReader()) 
     { 
      while (reader.Read()) 
      { 
       int temp = Convert.ToInt32(reader["cat_id"]); 
       right = rebuild_tree(temp, right); 
      } 

      command = conn.CreateCommand(); 
      command.CommandText = "UPDATE tbl_RefDataCategory_mst SET [email protected], [email protected] WHERE [email protected]"; 
      command.Parameters.Add("l", SqlDbType.Int).Value = left; 
      command.Parameters.Add("r", SqlDbType.Int).Value = right; 
      command.Parameters.Add("p", SqlDbType.Int).Value = parent; 

      command.ExecuteNonQuery(); 
     } 

     return right + 1; 
    }