【问题标题】:NHibernate - how to map collection of treesNHibernate - 如何映射树的集合
【发布时间】:2009-08-03 09:38:33
【问题描述】:

我想将我的对象模型映射到 NHibernate。我的概念中有一个棘手的部分,我不知道在 NHibernate 中是否可以做到这一点。

我想要一组树。我有两个类(下面,只指出了重要的属性)。 Component 是树的一个节点,ComponentGroup 是树的集合。

public class Component
{
    public Component Parent { get; set; }
    public IList<Component> SubComponents { get; set; }
    public ComponentGroup Group { get; set; }
}

public class ComponentGroup
{
    public IList<Component> Components { get; set; }
}

现在我希望每个 Component 都知道它属于哪个 ComponentGroup,因此我需要从每个 Component 引用 ComponentGroup(Group 属性)。但是 ComponentGroup 应该只有根节点(直接子节点)的集合 - 组件集合。所以这有点像一对半映射;)“一”方仅引用“多”方的某些项目。

你有什么想法如何使用 NHibernate 映射这样的东西吗?

【问题讨论】:

    标签: nhibernate mapping root treenode


    【解决方案1】:

    我会试一试(使用 FluentNHibernate 生成)

    <class name="Component" table="`Component`" xmlns="urn:nhibernate-mapping-2.2">
    <id name="ComponentId" type="Int32" column="ComponentId">
      <generator class="identity" />
    </id>
    <many-to-one name="Parent" column="ParentId" />
    <bag name="SubComponents">
      <key column="ComponentId" />
      <one-to-many class="NHibernateTests.Component, NHibernateTests, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null" />
    </bag>
    <many-to-one name="Group" column="GroupId" />
    

    <class name="ComponentGroup" table="`ComponentGroup`" xmlns="urn:nhibernate-mapping-2.2">
    <id name="Id" type="Int32" column="ComponentGroupId">
      <generator class="identity" />
    </id>
    <bag name="Components">
      <key column="ComponentGroupId" />
      <one-to-many class="NHibernateTests.Component, NHibernateTests, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null" />
    </bag>
    

    编辑:

    如果您希望所有组件都知道它们的 ComponentGroup ,那么在所有组件上设置 ComponentGroup 。

    如果你只想要所有的根组件,那么在 ComponentGroup 中将包更改为:

    <bag name="Components" where="ParentId is null"> 
    

    所以你只得到根组件

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-12-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多