【问题标题】:Mapping a Reflexive Many-to-Many relationship with NHibernate?使用 NHibernate 映射自反多对多关系?
【发布时间】:2012-09-10 15:09:48
【问题描述】:

我正在尝试将 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 类并只使用两个 many-to-one 关系更好?

【问题讨论】:

    标签: nhibernate nhibernate-mapping


    【解决方案1】:

    我可能遗漏了一些东西,但这应该可以帮助您开始:

    <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。

    【讨论】:

    • 非常感谢,这很好用。在网络上很难找到映射定义的具体示例。
    猜你喜欢
    • 2012-06-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-12-10
    • 2011-01-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多