Hash

Entries tagged as ‘linq’

Creating one-to-one relationship in NHibernate

November 18, 2008 · Leave a Comment

A one-to-one relationship between two tables can be created by:

  • Adding a column to the parent table with some unique ID of the child table
  • Without any extra column: just inserting the same PK value in both tables

NHibernate supports the second method (correct me) and you can create this relationship using the “foreign” type ID generator and the <one-to-one> tags in both mappings. Today I created the following mappings for two classes named Document and DocumentStatus.

<class name="Document" table="documents">
    <id name="Id" column="id">
          <generator class="foreign">
               <param name="property">Status</param>
          </generator>
    </id>
    <one-to-one name="Status" class="DocumentStatus" constrained="true"/>
    ... other properties ...
</class>

The trick here is just the foreign ID generator class. Now the mapping for DocumentStatus would be fairly simple.

<class name="DocumentStatus" table="documentstatus">
    <id name="Id" column="id">
       ... any generator class ...
    </id>
    <one-to-one name="Document" class="Document"/>
    ... other properties ...
</class>

The classes will have a property of the corresponding type to map this relationship so you can navigate both ways.

class Document {
... other stuff ...
DocumentStatus Status;
}
class DocumentStatus {
... other stuff ...
Document Document;
}

Whenver you insert a new object in Document, the corresponding DocumentStatus object will be created and its PK will be assigned to Document object as well.

Great Stuff!

Categories: .NET
Tagged: , , , , , , , ,