Can NHibernate's QueryOver syntax select MAX() of an SqlFunction?

自闭症网瘾萝莉.ら 提交于 2020-01-04 02:56:06

问题


I have registered an SQL function in my dialect subclass

RegisterFunction("addseconds", new SQLFunctionTemplate(NHibernateUtil.Date, "dateadd(second, ?1, ?2)"));

which can be used in queries like so

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

producing the SQL

SELECT dateadd(second,
               this_.DurationInSeconds,
               this_.StartTime) as y0_
FROM   [Event] this_

but what I'm really after is

SELECT MAX(dateadd(second,
               this_.DurationInSeconds,
               this_.StartTime)) as y0_
FROM   [Event] this_

unfortunately I can't seem to get SelectMax to take a Projections.SqlFunction. Can it be done?


回答1:


You need to update the NHUtil to be DateTime:

RegisterFunction("addseconds", new SQLFunctionTemplate(NHibernateUtil.DateTime, "dateadd(second, ?1, ?2)"));

Otherwise you will only be dealing with the Date portion.

Your query is fine, you just need to wrap it in a Projections.Max() like so:

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>();

I just quickly wrote a test, (different naming than above) and it produced the query:

SELECT max(dateadd(second,
                   this_.DurationInSeconds,
                   this_.SomeDate)) as y0_
FROM   Employee this_


来源:https://stackoverflow.com/questions/6867395/can-nhibernates-queryover-syntax-select-max-of-an-sqlfunction

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!