NHibernate 甚至支持这种查询。请参阅文档中的更多内容:15.8。分离查询和子查询 http://nhforge.org/doc/nh/en/index.html#querycriteria-detachedqueries。我们只需要拆分查询(如您的 SQL 片段中所示)分为两部分:
让我们假设,dbo.table1
问题中的映射为MyEntity
。
要创建内部选择,让我们使用DetachedCriteria
编辑(与小组一起扩展,SqlGroupProjection
)
有一个摘录SqlGroupProjection
method:
分组 SQL 投影,指定 select 子句和 group by
子句片段
// inner select
DetachedCriteria innerSelect = DetachedCriteria
.For(typeof(MyEntity))
.SetProjection(
Projections.ProjectionList()
.Add(
Projections.SqlGroupProjection(
" MAX(ID) ", // SELECT ... max(ID) only
" Prop1, Prop2, Prop3", // GROUP BY ... property1, p2...
new string[] {"ID"}, // could be empty, while not used for
new IType[] { NHibernate.NHibernateUtil.Int32 } // transformation
)
)
;
注意:我什至提供了最后两个参数,但在这种情况下它们可能为空:new string[], new IType[] {}
。这些仅用于转换(从数据具体化为实体)。事实并非如此,我们只是在构建内部选择......
// the select with IN clause
var result = session.CreateCriteria(typeof(MyEntity))
.Add(Subqueries.PropertyIn("ID", innerSelect))
.List<MyEntity>();
相关的还有15.7。预测、聚合和分组 http://nhforge.org/doc/nh/en/index.html#querycriteria-projection