Monday, January 26, 2009

Traversing Many-To-Many mappings with NHibernate Query Generator

We've been using the NHQG for awhile now, and we've had great success with it.

It wasn't until today that I found that the standard mapping using a Matches:

return Where.Interview.Attendees.Matches(Get.PersonSummary.ID, 
Where.PersonSummary.ID == RraPerson.GetCurrent().ID);

So I have a collection of PersonSummaries, which are mapped using a link table shown by the mapping below:

<idbag name="Attendees" table="InterviewAttendee">
  <collection-id type="Int32" column="ID">
    <generator class="native"/>
  <key column="InterviewID" />
  <many-to-many class="Namespace.PersonSummary, Assembly" column="PersonID"  lazy="false" />

Unfortunately this was not working and throwing an NHibby exception:

threw an exception of type 'NHibernate.QueryException'
base {NHibernate.HibernateException}: {"could not resolve property: Attendees of: Namespace.PersonSummary"

After some struggling I stumbled upon this blog post from Ayende which demonstrates how to perform a query against a many-to-many mapped collection. So my query now looked like:

return Where.Interview.Attendees.With().ID == RraPerson.GetCurrent().ID;

Sweet! The With() method works very nicely and even neatens up the query.

No comments:

Post a Comment