我正在尝试获取表中整数字段的最大值。具体来说,我正在尝试在添加新发票时自动递增“InvoiceNumber”字段。我不希望这是数据库中的自动增量字段,但是,因为它是由用户控制的 - 我只是想要处理默认情况。现在,我正在使用
session.CreateCriteria<Invoice>()
.SetProjection(Projections.Max("InvoiceNumber"))
.FutureValue<int>();
获取数据库中已有的最大发票号。这很有效,除非数据库中已有发票。然后我得到一个System.ArgumentException:值“”不是“System.Int32”类型,不能在这个泛型集合中使用。更改为FutureValue<int?>()
并未解决问题。有没有办法告诉NHibernate将空字符串映射为null?或者是否有更好的方法来完成我的目标?
异常的堆栈跟踪(至少是相关部分)是
NHibernate.HibernateException: Error executing multi criteria : [SELECT max(this_.[InvoiceNumber]) as y0_ FROM dbo.[tblInvoice] this_;
SELECT this_.ID as ID647_0_, this_.[NHVersion] as column2_647_0_, this_.[Description] as column3_647_0_, this_.[DiscountPercent] as column4_647_0_, this_.[DiscountDateDays] as column5_647_0_, this_.[PaymentDueDateDays] as column6_647_0_, this_.[Notes] as column7_647_0_, this_.[DiscountDateMonths] as column8_647_0_, this_.[PaymentDueDateMonths] as column9_647_0_, this_.[DiscountDatePeriod] as column10_647_0_, this_.[DiscountDateMonthlyDay] as column11_647_0_, this_.[DiscountDateMonthlyDayDay] as column12_647_0_, this_.[DiscountDateMonthlyDayMonth] as column13_647_0_, this_.[DiscountDateMonthlyThe] as column14_647_0_, this_.[DiscountDateMonthlyTheDOW] as column15_647_0_, this_.[DiscountDateMonthlyTheMonth] as column16_647_0_, this_.[DiscountDateMonthlyTheWeek] as column17_647_0_, this_.[PaymentDueDatePeriod] as column18_647_0_, this_.[PaymentDueDateMonthlyDay] as column19_647_0_, this_.[PaymentDueDateMonthlyDayDay] as column20_647_0_, this_.[PaymentDueDateMonthlyDayMonth] as column21_647_0_, this_.[PaymentDueDateMonthlyThe] as column22_647_0_, this_.[PaymentDueDateMonthlyTheDOW] as column23_647_0_, this_.[PaymentDueDateMonthlyTheMonth] as column24_647_0_, this_.[PaymentDueDateMonthlyTheWeek] as column25_647_0_ FROM dbo.[tblTermsCode] this_;
] ---> System.ArgumentException: The value "" is not of type "System.Int32" and cannot be used in this generic collection.
Parameter name: value
at System.ThrowHelper.ThrowWrongValueTypeArgumentException(Object value, Type targetType)
at System.Collections.Generic.List`1.VerifyValueType(Object value)
at System.Collections.Generic.List`1.System.Collections.IList.Add(Object item)
at NHibernate.Impl.MultiCriteriaImpl.GetResultsFromDatabase(IList results)
答案 0 :(得分:3)
使用... .UniqueValue<int?>();
NH在其MultiCriteria实现中使用非通用IList。用于FutureValue批处理。请参阅here了解List<int?>
无法通过IList实现添加null的原因。我很惊讶我以前从未遇到过这种情况。避免在Future或MultiCriteria中使用可空值类型。
答案 1 :(得分:1)
使用QueryOver API:
Session.QueryOver<T>()
.Select(Projections.Max<Statistic>(s => s.PeriodStart))
.SingleOrDefault<object>();
如果没有返回null,否则将结果转换为数字