2014-06-19 107 views
0

我想要做下面的SQL的NHibernate的等效 -NHibernate的查詢來獲取記錄匹配列的最大

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)匹配的記錄。

回答

2

這個怎麼樣:

// 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();