I’m working with the new version (2.0 GA) of NHibernate. The problem I have encountered today is about the composite-id.

Let’s say we have an entity that doesn’t have a personal id field. We don’t want to use the GUID or any other auto id generator class. We must implement the primary key logic in the corresponding table in the database. Now, imagine to have this table:

Key Column Name SQL Type Not null
yes Field01 varchar true
yes Field02 varchar true
yes Field03 varchar true
yes Field04 varchar true

At this point we will have a mapping XML in NHibernate in this way:


If we compile the DAL of our project, we will receive a fancy error:

“composite-id class must override Equals()”

“composite-id class must override GetHashCode()”

The explanation is very simple. We are saying that this class has 3 fields to implement a comparison so the NHB must know how you can compare these fields … and off course the CLR doesn’t know how to do it.

This is the solution in our entity:


There we go!! Now you have implemented a full version of the method “Hey is this the entity I’m going to save or is this entity brand new?!?!”

Personal Consideration.

In my opinion NHB should be able to override this method by itself via reflection and not to ask you to rebuild thousand of entities if you want to use the standard pattern active Record.

Comments are closed.

Post Navigation