views:

255

answers:

1

Hello, everyone!

We need to map simple class using NHibernate:

public class CatalogItem
{
    private IList<CatalogItem> children = new List<CatalogItem>();

    public Guid Id { get; set; }
    public string Name { get; set; }
    public CatalogItem Parent { get; set; }
    public IList<CatalogItem> Children
    {
        get { return children; }
    }        
    public bool IsRoot { get { return Parent == null; } }        
    public bool IsLeaf { get { return Children.Count == 0; } }
}

There are a batch of tutorials in the internet on this subject, but none of them cover little nasty detail: we need order to be preserved in Children collection. We've tried following mapping, but it led to strange exeptions thrown by NHibernate ("Non-static method requires a target.").

<?xml version="1.0" encoding="utf-8" ?>
<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2" namespace="Domain.Model" assembly="Domain">
    <class name="CatalogItem"  lazy="false">
        <id name="Id" type="guid">
            <generator class="guid" />
        </id>
        <property name="Name" />

        <many-to-one name="Parent" class="CatalogItem" lazy="false" />

        <list name="Children" cascade="all">
            <key property-ref="Parent"/>
            <index column="weight" type="Int32" />
            <one-to-many not-found="exception" class="CatalogItem"/>
        </list>        
    </class>
</hibernate-mapping>

Does anyone have any thoughts?

A: 

I'm no expert, but <key property-ref=...> looks strange to me in this usage. You should be able to do <key column="ParentID"/>, and NHibernate will automatically use the primary key of the associated class -- itself, in this case.

You may also need to set the list to inverse="true", since the relationship is bidirectional. [See section 6.8 in the docs.]

Dan Fitch