One-to-One association

One-to-one associations are the simplest kind of associations. They usually correspond to the foreign key relations when the foreign key column is the primary key column.

The following two cases are possible, when we map a one-to-one association.

Case 1. When the foreign key and the primary key in the dependent entity class (class, corresponding to the table that has the foreign key) consist of the same columns.

The database contains the Person and Contact tables, between which there is a foreign key created against the primary key fields of these tables.

Sample tables for the one-to-one association

We perform the following sequence of operations:

  • create an NHibernate model;

  • add the Person and Contact tables to the model.

As a result, we have the following model:

Model before creating an association

The association between the Person and the Contact entities looks as follows:

Configure association

Case 2. When the foreign key is some non-primary unique property. You have to specify the foreign key column of the constrained table in this case.

The database contains the Person and Contact tables, between which there is a foreign key that is created against the ContactID primary key field of the Contact table and the ContactID unique field of the Person table.

Sample tables without a primary key for the one-to-one association

We perform the following sequence of operations:

  • create an NHibernate model;

  • add the Person and Contact tables to the model;

  • display the Association Editor dialog and set the Separate Foreign Key parameter of the Contact property to True as well as set the Foreign Key column to the ContactID column.

The association between the Person and the Contact entities looks as follows:

Create association between tables

As a result, we have the following model:

Created model

See also

Overview

One-to-Many association

Many-to-Many association