Archive

Archive for September, 2008

Restricting types returned from a polymorphic query

September 19, 2008 Leave a comment

NHibernate is cool, I can map an inheritance hierarchy into my database, ask it to get me all instances of an object at the root of the hierarchy and NHibernate will automatically retrieve all subclasses and instantiate the actual (derived) type.  What does this mean in practice?

Demo class hierarchy

Demo class hierarchy

If I have the following class hierarchy and I query

“from Animal”

I will get a list of Animal instances back, but looking at the type of each returned instance will show that they are either Cocker Spaniel or West Highland Terrier.

For the most part, this behaviour is exactly what you need to leverage polymorphism in your design, however on the odd occasion, you need to limit the returned type from a polymorphic query (in my case it was to build a report). To achieve this you need to leverage the class meta-property and change your query to

“from Animal pet where pet.class = Cocker Spaniel”

The key to remember when using class is that you must reference it from the alias you assign to the type you want to restrict (e.g. pet in this example).

Categories: NHibernate
Follow

Get every new post delivered to your Inbox.