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

use*_*648 5 c# nhibernate nhibernate-mapping fluent-nhibernate nhibernate-criteria

我有以下数据模型:

Page
- Id      // Pk
- Type    // int

Section
- Id      // Pk
- Page    // Fk

Comment
- Id      // Pk
- Section // Fk
- Date    // DateTime
Run Code Online (Sandbox Code Playgroud)

我试图在一个时间限制内查询与某个页面相关的所有注释(Say page.id = 2和page.Type = 1).我试过这样的:

   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));
Run Code Online (Sandbox Code Playgroud)

但是,这会失败,因为我收到一条错误,说"无法解析属性:Page:TestNamespace.Comment".这通常表示映射错误,但它适用于所有其他情况,所以我倾向于相信错误在于查询.

更糟糕的是,在某些情况下,Comment.Section可能为null(有些注释与section或page无关).在那种情况下,我想忽略这些评论.

有什么建议?

谢谢!

Mel*_*igy 6

  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));
Run Code Online (Sandbox Code Playgroud)

我根据您的评论更新了代码。专门添加了第 2 行,第 3 行使用第 2 行中的别名而不是属性,依此类推。