NHibernate的QueryOver语法可以选择SqlFunction的MAX()吗?

twe*_*erq 3 .net c# sql nhibernate

我在我的方言子类中注册了一个SQL函数

RegisterFunction("addseconds", new SQLFunctionTemplate(NHibernateUtil.Date, "dateadd(second, ?1, ?2)"));
Run Code Online (Sandbox Code Playgroud)

可以在这样的查询中使用

var q = _session.QueryOver<Event>()
    .Select(
        Projections.SqlFunction(
            "addseconds",
            NHibernateUtil.Date,
            Projections.Property<Event>(x => x.DurationInSeconds),
            Projections.Property<Event>(x => x.StartTime)));
Run Code Online (Sandbox Code Playgroud)

生成SQL

SELECT dateadd(second,
               this_.DurationInSeconds,
               this_.StartTime) as y0_
FROM   [Event] this_
Run Code Online (Sandbox Code Playgroud)

但我真正追求的是

SELECT MAX(dateadd(second,
               this_.DurationInSeconds,
               this_.StartTime)) as y0_
FROM   [Event] this_
Run Code Online (Sandbox Code Playgroud)

不幸的是,我似乎无法让SelectMax采用Projections.SqlFunction.可以吗?

Phi*_*ill 7

您需要将NHUtil更新为DateTime:

RegisterFunction("addseconds", new SQLFunctionTemplate(NHibernateUtil.DateTime, "dateadd(second, ?1, ?2)"));
Run Code Online (Sandbox Code Playgroud)

否则您只会处理日期部分.

您的查询很好,您只需将它包装在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>();
Run Code Online (Sandbox Code Playgroud)

我刚刚写了一个测试,(不同于上面的命名),它产生了查询:

SELECT max(dateadd(second,
                   this_.DurationInSeconds,
                   this_.SomeDate)) as y0_
FROM   Employee this_
Run Code Online (Sandbox Code Playgroud)