2011-01-21 141 views
4

我需要從數據庫中獲取最大的頁面順序:如何在NHibernate中選擇最大值?

int maxOrder = GetSession.Query<Page>().Max(x => x.PageOrder); 

上述工程是否有數據庫中的錶行,但是當表爲空我越來越:

Value cannot be null. 
Parameter name: item 

回答

8
Session.Query<Page>().Max(x => (int?)x.PageOrder) 

注投(我假設PageOrder是一個int)

13

在您正在執行的方式是正常的,因爲枚舉類型爲GetSession.Query<Page>()返回的結果是空的(因爲表格是空的,因爲您提到過)。

您應該得到的異常是:序列不包含任何元素。 在你的問題中提到的異常是因爲item變量(與上面列出的NHiberanate查詢無關)爲空(第54行將item屬性指定爲null)。

一個更安全的方式來獲得一個表中的財產最高應爲以下:

var max = GetSession.CreateCriteria<Page>() 
       .SetProjection(Projections.Max("PageOrder")) 
       .UniqueResult(); 

或使用QueryOver與NHibenrate 3.0:

var max = GetSession.QueryOver<Page>() 
     .Select(
      Projections 
       .ProjectionList() 
       .Add(Projections.Max<Page>(x => x.PageOrder))) 
     .List<int>().First(); 

如果表是空的,你會獲得最大的= 0

+0

感謝ü了很多!有可能使用它的強類型版本? :) – Sasha 2011-01-21 13:00:23

+0

如果您使用NHibernate 3.0,則可以使用QueryOver。我編輯了我的答案,在QueryOver中添加了一個版本。 – tolism7 2011-01-21 13:45:32

5

如果您有由tolism7(InvalidCastException的)與QueryOver例題,這裏就是我得到了它的工作:

var max = session.QueryOver<Page>() 
    .Select(Projections.Max<Page>(x => x.PageOrder)) 
    .SingleOrDefault<object>(); 

return max == null ? 0 : Convert.ToInt32(max);