问题
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