NHibernate query against the key field of a dictionary (map)

Posted by Carl Raymond on Stack Overflow See other posts from Stack Overflow or by Carl Raymond
Published on 2010-05-04T22:19:59Z Indexed on 2010/05/04 22:28 UTC
Read the original article Hit count: 266

Filed under:

I have an object model where a Calendar object has an IDictionary<MembershipUser, Perms> called UserPermissions, where MembershipUser is an object, and Perms is a simple enumeration. This is in the mapping file for Calendar as

<map name="UserPermissions" table="CalendarUserPermissions" lazy="true" cascade="all">
  <key column="CalendarID"/>
  <index-many-to-many class="MembershipUser" column="UserGUID" />
  <element column="Permissions" type="CalendarPermission" not-null="true" />
</map>

Now I want to execute a query to find all calendars for which a given user has some permission defined. The permission is irrelevant; I just want a list of the calendars where a given user is present as a key in the UserPermissions dictionary. I have the username property, not a MembershipUser object. How do I build that using QBC (or HQL)? Here's what I've tried:

ISession session = SessionManager.CurrentSession;
ICriteria calCrit = session.CreateCriteria<Calendar>();
ICriteria userCrit = calCrit.CreateCriteria("UserPermissions.indices");
userCrit.Add(Expression.Eq("Username", username));
return calCrit.List<Calendar>();

This constructed invalid SQL -- the WHERE clause contained WHERE membership1_.Username = @p0 as expected, but the FROM clause didn't include the MemberhipUsers table.

Also, I really had to struggle to learn about the .indices notation. I found it by digging through the NHibernate source code, and saw that there's also .elements and some other dotted notations. Where's a reference to the allowed syntax of an association path? I feel like what's above is very close, and just missing something simple.

© Stack Overflow or respective owner

Related posts about nhibernate