我已经在我的方言子类中注册了一个 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_
关于c# - NHibernate 的 QueryOver 语法可以选择 SqlFunction 的 MAX() 吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6867395/