我在我的方言子类
中注册了一个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。可以吗?
答案 0 :(得分:7)
您需要将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_