How do I setup one-to-one relationship in nhibernate? (currently doesn't return the foreign object)

StackOverflow https://stackoverflow.com/questions/3857301

Question

I have a User, some of which are an employee. This is a one-to-one relationship and not all users are employees.

When I get a user it doesn't seem to be bring back the employee information it just has it marked as null. I thought I have got my head around nhibernate but I have tried playing with so many properties on the mapping files and haven't got it working. Any ideas or pointers as to what I am doing incorrect?

User Class:

public class User
    {
        public virtual int UserID { get; set; }
        public virtual string Username { get; set; }
        public virtual string Title { get; set; }
        public virtual string Forename { get; set; }
        public virtual string Surname { get; set; }

        public virtual Employee Employee { get; set; }
    }

User Mapping:

<?xml version="1.0" encoding="utf-8" ?>
<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2"
                   assembly="Portal.Core"
                   namespace="Portal.Core.Data.Database">

  <class name="User" table="[Users]">
    <id name="UserID">
      <generator class="identity" />
    </id>
    <property name="Username" not-null="true" length="50" />
    <property name="Title" length="10" />
    <property name="Forename" length="50" />
    <property name="Surname" length="50" />

    <one-to-one name="Employee" class="Employee" fetch="select" lazy="false" foreign-key="EmployeeID" />


  </class>

</hibernate-mapping>

Employee Class:

public class Employee
    {
        public virtual int EmployeeID { get; set; }
        public virtual string RoomNumber { get; set; }
        public virtual string JobTitle { get; set; }
        public virtual User User { get; set; }
    }

Employee Mapping:

<?xml version="1.0" encoding="utf-8" ?>
<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2"
                   assembly="Portal.Core"
                   namespace="Portal.Core.Data.Database">

  <class name="Employee" table="[Employees]">
    <id name="EmployeeID">
      <generator class="identity" />
    </id>
    <many-to-one name="User" unique="true" column="UserID" class="User" fetch="select" foreign-key="UserID" ></many-to-one>

    <property name="RoomNumber" length="20" />
    <property name="JobTitle" length="20" />

  </class>

</hibernate-mapping>
Was it helpful?

Solution

The only thing I can see is different from Ayende's example is that you specify a foreign-key tag. Maybe try stripping your mapping down to Ayende's example (Which by the way is the exact same scenario) and try adding the extra properties/attributes one by one?

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top