Search code examples
c#nhibernatenhibernate-mapping

NHibernate Many-To-One or am I missing something?


I've been wrestling with NHibernate 3.2 for a while now and all I am trying to achieve is something that I think should be relatively simple but can't seem for find a code example for.

All I want to have 2 objects.

public class ObjectA { 
    public int Id;
    public string PropertyA;
    public ObjectB PropertyB;
}

public class ObjectB {
    public int Id;
    public string PropertyA;
}

And on the database side I want

----
Table ObjectA
----
Column Id
Column PropertyA
Column ObjectBId
----

----
Table ObjectB
----
Column Id
Column PropertyA
----

I can't seem to get this to work and yet it should be trivial. I've tried using components but they seem to want to create only one table with all the fields from ObjectA and ObjectB combined. I've tried using one-to-one mapping but it wants me to compromise my object model by having a reference property in ObjectB back to ObjectA.


Solution

  • It is a really simple case:

    <class name="ObjectA">
       <id name="Id" access="property">
          <generator class="identity" />
       </id>
    
       <property name="PropertyA" />
       <many-to-one name="PropertyB" column="ObjectBId" class="ObjectB" />
    </class>
    
    <class name="ObjectB">
       <id name="Id" access="property">
          <generator class="identity" />
       </id>
    
       <property name="PropertyA" />
    </class>