NHibernate One-To-One

I have a one-to-one mapping problem. I searched the internet and found many solutions, but no one was satisfied. Most examples carry the overhead of storing the parent instance in the child class.

I want to use only the parent identifier in the child class that has the foreign key constraint relationship, but I do not want any parent instance to be a child.

When I try to load records from the database, it throws an exception "There is no row with this identifier [AssemblyName.]." But the record exists in table "B" properly.

Any solutions for this problem?

Class structure:

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

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] 

Display:

 <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> 
+6
source share
2 answers

Individual associations are always bi-directional at NHibernate. The 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 an association of foreign keys. For more information, see this Ayende blog post or NHibernate Documentation .

+4
source

Read this . The real one-to-one needs the same primary key in both tables (and without the Parent column).

0
source

Source: https://habr.com/ru/post/890970/


All Articles