我已经在我的方言子类中注册了一个SQL函数
RegisterFunction("addseconds", new SQLFunctionTemplate(NHibernateUtil.Date, "dateadd(second, ?1, ?2)"));
可以在像这样的查询中使用
var q = _session.QueryOver<Event>() .Select( Projections.SqlFunction( "addseconds", NHibernateUtil.Date, Projections.Property<Event>(x => x.DurationInSeconds), Projections.Property<Event>(x => x.StartTime)));
产生SQL
SELECT dateadd(second, this_.DurationInSeconds, this_.StartTime) as y0_ FROM [Event] this_
但是我真正想要的是
SELECT MAX(dateadd(second, this_.DurationInSeconds, this_.StartTime)) as y0_ FROM [Event] this_
不幸的是,我似乎无法让SelectMax接受Projections.SqlFunction。能做到吗
您需要将NHUtil更新为DateTime:
RegisterFunction("addseconds", new SQLFunctionTemplate(NHibernateUtil.DateTime, "dateadd(second, ?1, ?2)"));
否则,您将只处理日期部分。
您的查询很好,您只需将其包装在Projections.Max()中,如下所示:
var q = _session.QueryOver<Event>() .Select(Projections.Max(Projections.SqlFunction( "addseconds", NHibernateUtil.DateTime, Projections.Property<Event>(y => y.DurationInSeconds), Projections.Property<Event>(y => y.StartTime)))) .SingleOrDefault<DateTime>();
我刚刚快速编写了一个测试(与上面的命名不同),它产生了查询:
SELECT max(dateadd(second, this_.DurationInSeconds, this_.SomeDate)) as y0_ FROM Employee this_