【发布时间】:2018-04-23 05:50:40
【问题描述】:
我在数据库中有一个具有这样结构的表;
ID | Process_Id | Attribute | Parent_Id | Sequence
----------------------------------------------------
1 1 INDIVIDUAL
2 1 FIRST_NAME 1 1 //parent_id is same as ID of its parent
3 1 SECOND_NAME 1 2
4 1 INDIVIDUAL_ALIAS 1
5 1 ALIAS_NAME 4 1
6 2 sdnEntry
7 2 firstName 6 1
8 2 lastName 6 2
9 2 aka 6
10 2 firstName 9 1
11 2 lastName 9 2
12 1 ENTITY
13 1 FIRST_NAME 12 1
14 1 ENTITY_ALIAS 12
15 1 ALIAS_NAME 14 1
我为这些数据设置值的类如下所示;
将我之前的代码更新为DataAdapter
公共类属性
{
公共 int ProcessId { 获取;放; }
公共列表父节点 { 获取;放; }
}
public class ParentAttribute
{
public int id { get; set; }
public string parentNodeValue { get; set; }
public List<ChildAttribute> ChildNodeValues { get; set; }
}
public class ChildAttribute
{
public int sequence { get; set; }
public string childNodeValue { get; set; }
public int parentId { get; set; }
//public List<GrandChildAttribute> childNodeValue { get; set; }
}
public class GrandChildAttribute
{
public int sequence { get; set; }
public string grandChildNodeValue { get; set; }
public int parentId { get; set; }
}
这是我尝试在对象中放置值的方式,更新代码
public static Attribute GetProcessAttributes()
{
using (OracleConnection oCon = new OracleConnection(Con))
{
Attribute att = new Attribute();
string query = @"SELECT * from Process where Process_Id = :Process_Id";
OracleCommand cmd = new OracleCommand(query, oCon);
cmd.Parameters.AddWithValue("Process_Id", 1);
oCon.Open();
OracleDataReader rdr = cmd.ExecuteReader();
DataTable dt = new DataTable();
dt.Load(rdr);
if (dt.Rows.Count > 0)
{
foreach (DataRow row in dt.Rows)
{
att.ProcessId = Convert.ToInt32(row["Process_Id"]);
att.ParentNodes = new List<ParentAttribute>();
var pNodes = (from pRow in dt.AsEnumerable()
where pRow.Field<decimal?>("Parent_Id") == null
select pRow).ToList();
foreach (var pItem in pNodes)
{
ParentAttribute pAtt = new ParentAttribute();
pAtt.parentNodeValue = pItem["Attribute"].ToString();
pAtt.id = Convert.ToInt32(pItem["ID"]);
pAtt.ChildNodeValues = new List<ChildAttribute>();
var cNodes = (from cRow in dt.AsEnumerable()
where cRow.Field<decimal?>("Parent_Id") == pAtt.id
select cRow).ToList();
foreach (var cItem in cNodes)
{
//how to handle when childnode has further childs
ChildAttribute cAtt = new ChildAttribute();
if(cItem["Sequence"] == DBNull.Value)
{
cItem["Sequence"] = 0; //was unable to pass null value to Integer type in ternanry so did this
}
if (cItem["Parent_Id"] == DBNull.Value)
{
cItem["Parent_Id"] = 0;
}
cAtt.childNodeValue = cItem["Attribute"].ToString();
cAtt.sequence = Convert.ToInt32(cItem["Sequence"]);
cAtt.parentId = Convert.ToInt32(cItem["Parent_Id"]);
pAtt.ChildNodeValues.Add(cAtt);
}
att.ParentNodes.Add(pAtt);
}
}
}
return att;
}
}
现在我可以在我的对象中放置值,我将不胜感激,但问题是一些子节点有单个值,一些包含更多列表,我如何在运行时为该属性分配类型。
在我目前的情况下,两个父节点 "INDIVIDUAL" 和 "ENTITY" 每个父节点都有自己的子节点,由 parent_Id parent_Id 标识到 parentNodes 被视为 null 为空,进一步的孩子也有一些孙子节点。
【问题讨论】:
-
您想通过输入
Process_Id获取特定进程的所有父进程? -
父母和他们各自的孩子也
-
所以你需要递归迭代它,你知道如何递归吗?
-
@Aria 我更新了问题
标签: c#