Enyra
Enyra

Reputation:

How to map a self-reference in NHibernate

I have a very special NHibernate mapping case. The class has a reference to itself.

public class MyClass
{
   public Guid Id { get; set; }
   public MyClass SelfReference { get; set; }
}

The data base table has a foreign key field on the primary key of the same table. And event worse, this self reference can be null.

Is that possible to map and how can this be done?

Upvotes: 3

Views: 6740

Answers (4)

Frederik Gheysels
Frederik Gheysels

Reputation: 56934

Seems like you're willing to map a tree:

http://nhibernate.hibernatingrhinos.com/16/how-to-map-a-tree-in-nhibernate

Upvotes: 3

Stefan Steinegger
Stefan Steinegger

Reputation: 64628

one-to-one can be used to synchronize primary keys and is used rarely, in my experience many-to-one is the most "natural" association for "normal" references:

<many-to-one name="SelfReference" class="MyClass" column="SelfReference_FK" />

Upvotes: 3

Chen Kinnrot
Chen Kinnrot

Reputation: 21015

i think its a simple one-to-one.

i hope this will help u

<one-to-one
name="PropertyName"
class="ClassName"
cascade="all|none|save-update|delete"
constrained="true|false"
fetch="join|select"
property-ref="PropertyNameFromAssociatedClass"
access="field|property|nosetter|ClassName"/>

Upvotes: 0

Spencer Ruport
Spencer Ruport

Reputation: 35107

Seems like you'd just treat it the same as any other one-to-one relationship?

Upvotes: 0

Related Questions