简体   繁体   English

如何使用NHibernate Criteria API进行多个连接

[英]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. 我试图在一个时间限制内查询与某个页面相关的所有注释(Say page.id = 2和page.Type = 1)。 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". 但是,这会失败,因为我收到一条错误,说“无法解析属性:Page: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). 更糟糕的是,在某些情况下,Comment.Section可能为null(有些注释与section或page无关)。 In that case I want to ignore those comments. 在那种情况下,我想忽略这些评论。

Any advice ? 有什么建议?

Thanks! 谢谢!

  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. 具体添加了第2行,第3行使用第2行中的别名而不是属性,依此类推。

You can use additional CreateCriteria calls to navigate through the database structure 您可以使用其他CreateCriteria调用来浏览数据库结构

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM