C# – nHibernate ICriteria Join Condition

cnetnhibernate

I am trying to use ICriteria to create a query that has a join
condition. The SQL I am trying to generate should look like this

SELECT c.ClientID
FROM Client c
LEFT OUTER JOIN ClientContact t on c.ClientID = t.ClientID AND
t.ContactType = 'Email'

If I use a criteria like

m_ClientRepository.QueryAlias("client")
     .CreateCriteria("client.Contacts", "c", JoinType.LeftOuterJoin)
     .Add(Restrictions.Eq("c.ContactType", ContactType.Email));

It will generate the sql below which I don't want.

SELECT c.ClientID
FROM Client c
LEFT OUTER JOIN ClientContact t on c.ClientID = t.ClientID
WHERE t.ContactType = 'Email'

Is there anyway to do this with ICriteria or HQL if ICriteria is not possible ?

Edit: I have discovered nHibernate 2.1 (which I am using) does now allow this. Not sure about ICriteria though, this is my preference.

Best Answer

I wouldn't do this. The left outer join let's NH load clients anyway, the filter for E-Mail contacts would load only E-Mail contacts ... until it initializes the contact collection and loads everything anyway.

If it would load only E-Mail contacts, it would end up in incomplete objects in memory. This is usually not a good idea, particularly when you are also changing data in the same transaction.

In your situation I would try to load EMail contacts directly and navigate from the contact to the customer.

session.CreateCriteria(typeof(Contact))
     .Add(Restrictions.Eq("c.ContactType", ContactType.Email));