views:

186

answers:

1

Hi,

I want map my object model to NHibernate. There is one tricky part in my concept and I don't know if it is possible to do this in NHibernate.

I want to have a collection of trees. I have two classes (below, only important properties indicated). Component is a node of a tree and ComponentGroup is a collection of trees.

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; }
}

Now I want each Component to know which ComponentGroup it belongs to, so I need reference from every Component to ComponentGroup (Group property). But ComponentGroup should have only collection of root nodes (direct children) - Components collection. So this is something like one-to-half mapping ;) "one" side has reference only to some items from "many" side.

Do you have any ideas how to map something like this using NHibernate?

A: 

I'll give it a shot (generated with 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>

EDIT:

If you want all your Components to know their ComponentGroup then set on all of them the ComponentGroup .

And in ComponentGroup if you want all the root components only then change the bag to :

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

so you only get the root components

sirrocco
That's exactly what I need, thanks!
kuba53280
Glad I could help :)
sirrocco

related questions