开发者

NHibernate One-To-One

开发者 https://www.devze.com 2023-03-14 10:58 出处:网络
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'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="strin开发者_如何学运维g"> <generator class="assigned"/> </id>
<property name="_Name" column="Name"/> </class> 
</hibernate-mapping>


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.


Read this. A "real" one-to-one needs the same primary key in both tables (and no ParentId column).

0

精彩评论

暂无评论...
验证码 换一张
取 消