NHibernate的QueryOver语法选择SqlFunct

NHibernate的QueryOver语法选择SqlFunct

本文介绍了可以NHibernate的QueryOver语法选择SqlFunction的MAX()?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

生产SQL

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_

不幸的是我似乎无法得到SelectMax采取Projections.SqlFunction。能不能做到?

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

推荐答案

您需要更新NHUtil是日期时间:

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.

您查询的是好的,你只需要包装在一个Projections.Max()像这样:

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_

这篇关于可以NHibernate的QueryOver语法选择SqlFunction的MAX()?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-21 00:35