Home > NHibernate > Restricting types returned from a polymorphic query

Restricting types returned from a polymorphic query

September 19, 2008 Leave a comment Go to comments

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).

Advertisement
Categories: NHibernate
  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

Gravatar
WordPress.com Logo

Please log in to WordPress.com to post a comment to your blog.

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.