2013-10-22 40 views
1

我如何在NHibernate中表達這一點?NHibernate中的Where子句

DECLARE @EntityId INT = 800; 

SELECT * 
FROM UserAlert 
WHERE UserAlertId = 
        (
        SELECT MAX(UserAlertId) 
        FROM UserAlert 
        WHERE EntityId = @EntityId 
       ) 

這就是我想要做的。

var senderUA = session.CreateCriteria<UserAlert>() 
         .Add(Restrictions.Eq("EntityId", id)) 
         .SetProjection(Projections.Max("Id")) 
         . UniqueResult(); 

我不斷收到一個錯誤,可以將對象轉換爲UserAlert類型,即它甚至不編譯。

感謝您的幫助

回答

3

排序方式UserAlertId下降並選擇頂部1會更簡單。

var senderUA = session.CreateCriteria<UserAlert>() 
        .Add(Restrictions.Eq("EntityId", id)) 
        .AddOrder(Order.Desc("UserAlertId")) 
        .SetMaxResults(1) 
        .UniqueResult(); 

此外,您可以

var senderUA = session 
        .Query<UserAlert>() 
        .Where(x=>x.EntityId==id && 
         x.UserAlertId==session.Query<UserAlert>() 
              .Where(x=>x.EntiryId==id).Max(x=>x.UserAlertId) 
         ).FirstOrDefault(); 
0

下面是使用QueryOver的解決方案。

var maxUserAlertId = QueryOver.Of<UserAlert> 
          .Where(ua => ua.EntityId == id) 
          .Select(
           Projections.Max(
            Projections.Property<UserAlert> 
                 (u => u.UserAlertId) 
           ) 
           ); 
var maxUserQuery = session 
        .QueryOver<UserAlert>() 
        .WithSubquery 
         .WhereProperty(u => u.EntityId) 
         .Eq(maxUserAlertId); 

// Dealing with the situation that the maximum value is shared 
// by more than one row. If you're certain that it can only 
// be one, call SingleOrDefault instead of List 
IList<UserAlert> results = maxUserQuery.List();