Monthly Archives: February 2010

NHibernate: How to filter on primitive collections

I am using NHibernate with a client and I keep hitting the same issue. I have entities with basic collections of strings. I want to search for entities on the basis of filtering criteria expressed against the elements of the collection.

The easy solution is to treat the collection elements as entities but this is not ideal. That really complicates the domain. In some cases, the elements are simply references to foreign entities outside the scope of NHibernate, for example in a remote service or configuration file.

In SQL, I can pose the query as a correlated subquery or as an (outer) join. This has the advantage of being efficient and does not result in the loading of the collection.

An example would be searching for a Cat that is only black when each Cat has a collection of Colours, perhaps represented by an RGB triad. It would be true normal form to extract the colours into their own table but it would also be ridiculous to do so because a foreign key already exists – the RGB triad! Another example would be finding all Cats that are partly black or partly white. There is no reason why the criteria cannot be arbritrarily complex.

I have not found a way in HQL or the Criteria API and my scenarios require the filtering to take place in the database. The result is that I am using SQL directly with NHibernate’s ISession.

Any better solutions? Does ADO.NET Entity Framework also lack this concept?

Advertisements

Introducing SQL Service Broker

I have been investigating SQL Server’s Service Broker component as a possible choice for enabling messaging solutions in a .Net environment for a client and I have been impressed by the feature set.

The architecture does require a bit of a mind shift as it encourages the separation of processing logic from the reception of messages. Sending messages should of course still be part of the process logic.

Why this distinction? This approach allows for rapid verification of message transfer and controlled processing of message content. It encourages developers to recognise that transfer of messages is a different task to responding to a queue of received requests. Messaging is about sending messages and reliably receiving them, not about any particular business process.

If you do not apply this design then you are in danger of causing rollbacks during message reception and this may stop a queue if it occurs five times in a row.

Do you agree with the design? What are your experiences?