Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to do multiple joins with NHibernate Criteria API

I have the following data model:

Page
- Id      // Pk
- Type    // int

Section
- Id      // Pk
- Page    // Fk

Comment
- Id      // Pk
- Section // Fk
- Date    // DateTime

I'm trying to query all comments that are associated with a certain Page (Say page.id = 2 and page.Type = 1) within a time limit. I tried it like this:

   var criteria = session.CreateCriteria<Comment>()

   .Add(Restrictions.Eq("Section.Page.Id", pageId))
   .Add(Restrictions.Eq("Section.Page.Type", pageType))
   .Add(Restrictions.Ge("Date", start))
   .Add(Restrictions.Lt("Date", end));

However, this fails as I get an error says "could not resolve property: Page of: TestNamespace.Comment". This normally would indicate mapping errors, but it works in all other cases, so I'm inclined to belive the error lies in the query.

To make matters worse, Comment.Section might be null in some cases (there are comments that are not associated with a section nor page). In that case I want to ignore those comments.

Any advice ?

Thanks!

like image 218
user315648 Avatar asked Sep 05 '11 14:09

user315648


1 Answers

  var criteria = session.CreateCriteria<Comment>()
     .CreateAlias("Section", "section")
     .CreateAlias("section.Page", "page")
     .Add(Restrictions.Eq("page.Id", pageId))
     .Add(Restrictions.Eq("page.Type", pageType))
     .Add(Restrictions.Ge("Date", start))
     .Add(Restrictions.Lt("Date", end));

I updated the code based n your comment. The 2nd line specifically was added, and the 3rd line is using the alias in 2nd line instead of the property, and so on.

like image 64
Meligy Avatar answered Oct 17 '22 23:10

Meligy