NHibernate查询以获取与列的最大值匹配的记录

时间:2014-06-19 08:35:30

标签: c# asp.net nhibernate

我想在nHibernate中执行以下SQL的等效操作 -

SELECT * FROM healthcheckreports 
WHERE timestamp = (SELECT max(timestamp) 
  FROM healthcheckreports;

我可以使用以下内容获取max(timestamp)

var criteria = session.CreateCriteria<HealthCheckReport>();
criteria.SetProjection(Projections.Max("TimeStamp"));
criteria.UniqueResult();

但我想要的是时间戳与max(timestamp)匹配的记录。

1 个答案:

答案 0 :(得分:3)

这个怎么样:

// the inner (sub) select resulting in just max TimeStamp
var maxTimestamp = DetachedCriteria.For<HealthCheckReport>()
    .SetProjection(Projections.Max("TimeStamp"));

// the root query with a WHERE
var criteria = session.CreateCriteria<HealthCheckReport>()
    .Add(Subqueries.PropertyEq("TimeStamp", maxTimestamp));

// the most fresh one
var result = criteria
    .UniqueResult();