2012-09-10 57 views
1

我想用现有的数据库使用NHibernate。该数据库记录用户之间的单向关系:映射与NHibernate的自反多对多关系?

Users 
    UserId    PK 
    Name 

Relationships 
    RelationshipId  PK 
    ParentId   FK:Users_UserId 
    ChildId    FK:Users_UserId 

我想用NHibernate来表示这个。目前,我有以下POCO对象:

class User { 
    public virtual int Id { get; set; } 
    public virtual string Name { get; set; } 

    public ICollection<User> ParentUsers {get; set;} 
    public ICollection<User> ChildUsers {get; set;} 
} 

我也有这个映射文件:

<class name="User" table="Users"> 
    <id name="Id"></id> 
    <property name="Name"></property> 
</class> 

我看了网络上的指南,但我不知道是什么我需要放置映射文件来连接我的两个ICollection属性。

我应该如何映射这个数据结构?我目前的方法是否正确,还是创建第二个POCO课程更好?只需使用两个关系?

回答

2

我可能失去了一些东西,但是这应该让你开始:

<idbag name="ParentUsers" table="Relationships"> 
    <collection-id column="RelationshipId" type="..."> 
    <generator class="..."/> 
    </collection-id> 
    <key column="ChildId"/> 
    <many-to-many column="ParentId" class="User"/> 
</idbag> 
<idbag name="ChildUsers" table="Relationships"> 
    <collection-id column="RelationshipId" type="..."> 
    <generator class="..."/> 
    </collection-id> 
    <key column="ParentId"/> 
    <many-to-many column="ChildId" class="User"/> 
</idbag> 

而且,其中一个集合应标记为inverse

+1

感谢一大堆,这工作正常。在网络上定义映射的定义很难找到具体的例子。 – Oliver