http://www.agilelabs.cn/blogs/linkin/archive/2006/05/14/1212.aspx
使用Castle ActiveRecord生成树形结构
原本有点担心AR对树这种比较复杂的数据结构无法支持,结果竟然发现很容易。
代码如下:
[ActiveRecord("Tree")]
public class Tree : ActiveRecordBase<Tree>
{
int id;
[PrimaryKey(PrimaryKeyType.Native, "ID")]
public int ID
{
get { return id; }
set { id = value; }
}
IList children = new ArrayList();
[HasMany(typeof(Tree), "ParentID", "Tree", Cascade=ManyRelationCascadeEnum.All)]
public IList Children
{
get { return children; }
set { children = value; }
}
Tree parent;
[BelongsTo("ParentID")]
public Tree Parent
{
get { return parent; }
set { parent = value; }
}
}
简单吧?只要在类定义中设置一对多的“自引用”关系,就创建出了一个树的数据结构,对应的数据库脚本如下(AR自动生成的):
CREATE TABLE [dbo].[Tree](
[ID] [int] IDENTITY(1,1) NOT NULL,
[ParentID] [int] NULL,
PRIMARY KEY CLUSTERED
(
[ID] ASC
)WITH (IGNORE_DUP_KEY = OFF) ON [PRIMARY]
) ON [PRIMARY]
用法也非常的“面向对象”:
Tree root = new Tree();
Tree child = new Tree();
Tree grandChild = new Tree();
root.Children.Add(child);
child.Children.Add(grandChild);
root.Save();
保存在在数据表中的结果是:
ID ParentID
1 NULL
2 1
3 2