如何使用ActiveRecord在同一个表上设置父子关系?

时间:2008-12-20 05:32:16

标签: parentid

如何在同一张桌子上设置父子关系?

Id int, 
title string, 
ParentId int  ---> this is refer to Id

1 个答案:

答案 0 :(得分:2)

您使用的ActiveRecord实现是什么?

Castle ActiveRecord中,如果您的表格如下所示:

table Document (
   Id int primary key,
   ParentDocumentId int,
   Title string
)

您将使用以下语法:

[ActiveRecord(Table = "Document")]
public class Document : ActiveRecordBase<Document> {

    private int id;
    private Document parent;
    private string title;
    private List<Document> children = new List<Document>();

    [PrimaryKey]
    public int Id {
        get { return id; }
        set { id = value; }

    }

    [BelongsTo("ParentDocumentId")]
    public virtual Document Parent {
        get { return parent; }
        set { parent = value; }
    }

    [HasMany(Table = "Document", ColumnKey = "ParentDocumentId", Inverse = true, Cascade = ManyRelationCascadeEnum.All)]
    public IList<Document> Children {
        get { return children.AsReadOnly(); }
        private set { children = new List<Document>(value); }
    }

    [Property]
    public string Title {
        get { return title; }
        set { title = value; }
    }
}