Mapping - Child with multiple parents

1 view
Skip to first unread message

Tim

unread,
Jan 28, 2010, 12:32:15 AM1/28/10
to nhusers
Hi All,

I need some help on correctly mapping the below scenario in NH:

I have a Category class. Category can have many child categories.
Child categories can also be map to many parent categories. In
addition, a category can have no parent (meaning its a root category)
and have no child.

The class structure is like this:

public class Category
{
public virtual string Name { get; set; }

public virtual IList<Category> Parents { get; protected set; }
public virtual IList<Category> Children { get; protected
set; }
}

The mapping I created is this:

<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2" default-
access="property" auto-import="true" default-cascade="none" default-
lazy="true">
<class xmlns="urn:nhibernate-mapping-2.2"
name="Portal.Domain.Models.Catalog.Category, Portal.Domain,
Version=1.0.0.0, Culture=neutral, PublicKeyToken=null"
table="Categories">
<id name="Id" type="System.Int32, mscorlib, Version=2.0.0.0,
Culture=neutral, PublicKeyToken=b77a5c561934e089">
<column name="CategoryId" />
<generator class="identity" />
</id>
<bag inverse="true" lazy="true" name="Parents"
table="CategoryParents">
<key>
<column name="ParentCategoryId" />
</key>
<many-to-many
class="Laurysis.Portal.Domain.Models.Catalog.Category,
Laurysis.Portal.Domain, Version=1.0.0.0, Culture=neutral,
PublicKeyToken=null">
<column name="ChildCategoryId" />
</many-to-many>
</bag>
<bag cascade="save-update" lazy="true" name="Children"
table="CategoryParents">
<key>
<column name="ChildCategoryId" />
</key>
<many-to-many
class="Laurysis.Portal.Domain.Models.Catalog.Category,
Laurysis.Portal.Domain, Version=1.0.0.0, Culture=neutral,
PublicKeyToken=null">
<column name="ParentCategoryId" />
</many-to-many>
</bag>
</class>
</hibernate-mapping>

My main problem is I don't know how to create a query that will return
only all the categories (root categories) what has no parent category,
and also return categories with no child categories.

So far I tried using these following queries (using Linq to NH):

from c in Session.Linq<Category>()
where c.Parents.Count == 0
select c

from c in Session.Linq<Category>()
where c.Parents == null
select c

Any ideas? TIA.

Reply all
Reply to author
Forward
0 new messages