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?
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?
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");
}
}
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")
}
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...:-)