Nhibernate

NHibernate is an ORM (object relation mapper) for .NET inspired by Hibernate.

In these code examples I will use the basic xml configuration.

Relationships

Relationships in NHibernate are very tightly related to relationships in a SQL database.

One to Many Associations

  • One to Many Relationships <set><one-to-many class="Order"/></set> two tables and an FK CustomerId in Order table
  • Many to One Relationship ** <many-to-one name="Customer"/>
  • Many to many two tables and an FK CustomerId in Order table <many-to-many/> ** joining table with two FKs, one to each related table
1
2
3
4
5
6
7
8
9
10
11
12
<!-- Customer -->
<set name="Orders" table="`Order`">
    <key column="CustomerId"/>
    <one-to-many class="Order" />
</set>
<set name="Addresses" table="Address">
    <key column="CustomerId"/>
    <many-to-many column="AddressId" class="Address"/>
</set>

<!-- Order -->
<many-to-one name="Customer" column="CustomerId"/>

One to One Association

Relationship where two tables share the same PK.

1
2
<!-- Customer -->
<one-to-one name="Person"/>

References

Comments