adrianos
adrianos

Reputation: 1561

nhibernate reference parent class in child class

Is it possible to refer to a parent object in a child object using nhibernate? What I have been doing up until now is putting the parent Id in the child class, allowing me to determine what the parent of any child is at runtime.

Someone has told me that I can instead refer to the entire parent object in my child, and not just the parent id, without running into recursion issues.

What I currently do is this:

Child child = (Child)session.Get(typeof(Child), childId);

Then I can get hold of my parentId like so:

int parentId = child.ParentId;

What I want to do is this:

Child child = (Child)session.Get(typeof(Child), childId);

int parentId = child.**Parent**.Id;

string parentName = child.**Parent**.Name

Here is an example of how I define my classes

public class Parent
{
public int Id { get; set; }
public string Name { get; set; }

// A list of child objects
public IList<Child> Children { get; set; }
}

public class Child
{
public int Id { get; set; }
public string Name { get; set; }
public int ParentId { get; set; } // this is what I use now 

// public Parent MyParent { get; set; } // this is what I want to use
}

My nHibernate mapping files:

   <class name="Parent" table="parents" lazy="false">
        <id name="Id">
            <generator class="identity" />
        </id>
        <property name="Name" />
        <bag name="Children" cascade="all" lazy="false" >
            <key column="ParentId" />
            <one-to-many class="Child"/>
        </bag>

        <!-- Do I put anything in here to refer to my parent object in my child object?-->
    </class>


   <class name="Child" table="Children" lazy="false">
        <id name="Id">
            <generator class="identity" />
        </id>
        <property name="ParentId" />
        <property name="Name" />

        <!-- Do I put anything in here to refer to my parent object in my child object?-->
    </class>

Any help gratefully appreciated!

Upvotes: 1

Views: 1295

Answers (1)

zoidbeck
zoidbeck

Reputation: 4151

sure this is possible:

<!-- Set inverse to true on the one-to-many to tell 
     NHibernate this relation is mapped from both sides -->
<bag name="Children" cascade="all" lazy="false" inverse="true">
    <key column="ParentId" />
    <one-to-many class="Child"/>
</bag>

<class name="Child" table="Children" lazy="false">
    <id name="Id">
        <generator class="identity" />
    </id>
    <property name="ParentId" />
    <!-- Use this to map the Parent object -->
    <many-to-one name="MyParent" class="Parent" column="ParentId"/>
<property name="Name" />
    </class>

Upvotes: 2

Related Questions