WILT: Query by Criteria with clause on component property with NHibernate


It took me a little bit to figure this one out but it makes sense and it’s pretty simple once we know:

Let’s say I have a class MyFirstClass with a component of type MySecondClass and I want to write a query to retrieve all MyFirstClass objects where the ID of MySecondClass is 1.
My first attempt went like this:

Session.CreateCriteria(typeof(MyFirstClass)
   .Add(NHibernate.Criterion.Expression
     .Eq("MySecondClass.ID", "1"));
That didn’t work because NHibernate doesn’t understand what I meant with MySecondClass.ID.
The solution is simply to use a sub criteria like so:
Session.CreateCriteria(typeof(MyFirstClass)
  .CreateCriteria("MySecondClass")
    .Add(NHibernate.Criterion.Expression
      .Eq("ID", "1"));

It is important to notice that the sub criteria is created using the Property name

Advertisements

Leave a Reply

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

WordPress.com Logo

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

Twitter picture

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

Facebook photo

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

Google+ photo

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

Connecting to %s

%d bloggers like this: