Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NHibernate One-To-One

Tags:

nhibernate

I've an issue using one-to-one mapping. I've searched internet and found many solutions but none was satisfying. Most of the examples carry overhead of storing parent instance in child class.

I want to use only parent Id in child class having foreign key constraint relationship but dont want to keep any parent instance in child.

When I try to load the records from database it throws exception "No row with the given identifier exists [AssemblyName.]". But, the record exists in Table "B" properly.

Any solutions for this issue?

The class structure:

class A { 
public virtual string Id {get;set;} 
public virtual B B {get;set;} // properties...... } 

class B { public virtual string Id {get;set;} // properties...... 
public virtual string ParentId { get;set;} // class A Id }

The database structure:

CREATE TABLE [A]( 
    [Id] [nvarchar](45) PRIMARY KEY
) ON [PRIMARY] 

CREATE TABLE [B]( 
    [Id] [nvarchar](45) PRIMARY KEY, 
    [ParentId] [nvarchar](45) NOT NULL
) ON [PRIMARY]

The mapping:

<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2"> 
<class name="A,AssemblyName" table="A" lazy="true">
<id name="Id" column="Id" type="string"> 
<generator class="assigned"/> 
</id> 
<one-to-one name="_B" cascade="all" fetch="join" foreign-key="None" constrained="true" class="B"/> 
</class> 
</hibernate-mapping>


<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2">
<class name="B,AssemblyName" table="B" lazy="true"> 
<id name="Id" column="Id" type="string"> <generator class="assigned"/> </id>
<property name="_Name" column="Name"/> </class> 
</hibernate-mapping>
like image 848
ni3a Avatar asked Jun 21 '11 01:06

ni3a


1 Answers

One-to-one associations are always bidirectional in NHibernate. Mapping of class B is incomplete:

<class name="B,AssemblyName" table="B" lazy="true"> 
   <id name="Id" column="Id" type="string">
      <generator class="assigned"/>
   </id>
   <many-to-one name="A" unique="true" column="A" />
   <property name="_Name" column="Name"/>
</class>

This is foreign key association. For more information see this detailed Ayende's blog post or NHibernate documentation.

like image 84
Jakub Linhart Avatar answered Oct 19 '22 23:10

Jakub Linhart