It might be very simple but I think I am missing something. I have a self joined table Units, every unit has a main unit:

So that I could query for something like this:

The table units is mapped to the following class:
public class Units
{
public virtual int Unit_Id { get; private set; }
public virtual string Unit { get; set; }
public virtual decimal Unit_Value { get; set; }
public virtual Units Main_Unit { get; set; }
}
With .hbm mapping file as follows:
<?xml version="1.0" encoding="utf-8" ?>
<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2" assembly="NewA.Domain" namespace="NewA.Domain">
<class name="NewA.Domain.Entities.Units,NewA.Domain" table="Units">
<id name="Unit_Id" column="Unit_Id" type="Int32" length="4" unsaved-value="0">
<generator class="native">
</generator>
</id>
<property name="Unit" column="Unit" type="string" length="50" not-null="true"/>
<one-to-one name="Main_Unit" class="NewA.Domain.Entities.Units,NewA.Domain"/>
</class>
</hibernate-mapping>
When testing these entity with the following code:
Units unit = _UnitsRepository.GetById(2);
string parent_unitname = unit.Main_Unit.Unit;
Assert.AreEqual("pack",parent_unitname);
I got the following excpetion:
Expected values to be equal. Expected Value : "pack" Actual Value : "kg"
The problem is that the Main_Unit property of the Unit entity is referencing itself, so what I am missing here??, and how can I write something like recursive SQL CTE to apply ranks and so on, because I have the same problem with other more complex self joined tables with more complex queries.
You need many-to-one mapping instead one-to-one.
Try this configuration:
I suggest you to try Fluent NHibernate – it can dynamically generate mappings for you.
Here’s the configuration I used: