tags:

views:

1654

answers:

3

I have a table called "Orderrow". Orderrow has a a compound primary key (CPK) with the following columns: OrderId, ProductId, RowNumber

OrderId and ProductId are also foreign keys refering to the tables Order and Product. The RowNumber is generated in the app.

I was wondering how this is mapped in NHibernate because I can only set 1 id element and 1 generator subelement.

+3  A: 

There is a 'composite-id' property you can use in your class mapping instead of the 'id' property. However, you should know that the nHibernate team strongly discourages the use of it. It sounds like you are dealing with a legacy database, in which you have no control over the schema. So, the 'composite-id' is specifically for your situation.

Check out the NH docs for more info: http://nhforge.org/doc/nh/en/index.html

NathanD
I read that too in the NHibernate API ref. But I do not have a "legacy" database, just a database for research purpose so I can easly change the Orderrow table here. So what is the preferred better option in table design then ? Should I create 1 primary key on the table Orderrow that is unique per row ?
Patrick Peters
Yes. A single unique column for primary is preferable.
NathanD
A: 

Personally I do not like to have compound primary keys in my database table schemas, plus they usually are 'hard' to handle by any ORM mapper I tried. If I have to give a unique identity to a row in a table (especially if it represents a business object), I prefer to use a single value surrogate Id - a GUID or an Integer - if any of the fields in the table isn't suitable. Using a composite Id is always troublesome when writing interrogation queries and joins, so my usual strategy is to use a surrogate Id (which has no meaning to the business object but to identify the object itself) and place a unique constraint on the fields of the previous CPK.

A: 

Here is an example using the composite-id property in a NHibernate mapping file:

<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2" assembly="Domain" namespace="Domain.Model">

  <class name="Program" table="program">
    <composite-id>
      <key-property name="Id" column="id"></key-property>
      <key-property name="Prog" column="prog"></key-property>
      <key-property name="Site" column="site"></key-property>
    </composite-id>
    <property name="ActiveDate" column="active_date"/>
    <property name="Year" column="year"/>
  </class>

</hibernate-mapping>
Dan