4

I have a table with 2 columns as PK (composite primary key).

How can I map them to "Id" in hbm.xml?

<id name="A" />  

How can I do it with fluent nhibernate?

Oded
  • 489,969
  • 99
  • 883
  • 1,009
Elad Benda
  • 35,076
  • 87
  • 265
  • 471

3 Answers3

13

The NHibernate documentation describes how to use and map a composite-id.

You can also use a component as compositeid.

And for Fluent NHibernate:

public class ClassNameMap: ClassMap<ClassName>
{
    public ClassNameMap()
    {
        CompositeId().
            .KeyReference(x => x.A, "A")
            .KeyReference(x => x.B, "B");
    }
}
Owen Pauling
  • 11,349
  • 20
  • 53
  • 64
Gerard
  • 2,461
  • 2
  • 26
  • 34
  • The references are not working anymore. It is better do copy the answer here, supported by references, than just using references only. – Martin Mulder Oct 21 '15 at 13:18
5

For a composite primary key in nHibernate I would suggest;

For the hbm.xml:

<hibernate-mapping>   
<class table="TableName" name="Namespace.ClassName, ClassName">
<composite-id>
    <key-property name="IdPropertyOne" column="ColumnOne" />
    <key-property name="IdPropertyTwo" column="ColumnTwo" />
</composite-id>
<property name="PropertyName" column="ColumnName" type="String"></property>
</class>
</hibernate-mapping>

And then you should override Equals and GetHashCode methods, so that nHibernate knows how to compare your new key and identify different objects. It depends on how far you are willing to go, you can as well map foreign keys on these by using "key-many-to-one".

For a key-many-to-one:

<key-many-to-one name="PropertyOneObjName" column="ColumnOne" class="PropertyOneClassName">

For fluent hibernate a composite key looks like:

public ClassName(){
    CompositeId().
        KeyProperty(x => x.IdPropertyOne,"ColumnOne")
        KeyProperty(x => x.IdPropertyTwo,"ColumnTwo")
}
mmg666
  • 353
  • 1
  • 12
1

try this for NHibernate...

<composite-id name="Key" class="KeyClass"> 
  <key-many-to-one name="first" column="firstColumn" lazy="proxy" class="FirstClass"/>
  <key-many-to-one name="second" column="secondColumn" lazy="proxy" class="SecondClass"/>
</composite-id>

and for fluent Hibernate

<composite-id>  
  <key-property type="Int32" name="first" column="firstColumn" />  
  <key-property type="Int32" name="second" column="secondColumn" />  
</composite-id>  

hope that helps you...:-)

mikeschuld
  • 943
  • 1
  • 11
  • 25
Abhishek bhutra
  • 1,400
  • 1
  • 11
  • 29