开发者

NHibernate: how to express a specific "group by" query with criteria

Question:

What are the开发者_高级运维 criteria/projections that can generate a following query?

SELECT SUBSTRING(Name, 0, 1) FROM Person GROUP BY SUBSTRING(Name, 0, 1)

(Obviously this one is easier with DISTINCT, but I'll need counts later, when I fix this one).


My approaches:

My main problem here is with constants, because if I use

Projections.GroupProperty(Projections.SqlFunction(
   "SUBSTRING",
   NHibernateUtil.String,
   Projections.GroupProperty("Name"),
   Projections.Constant(0),
   Projections.Constant(1)
))

I get

SELECT SUBSTRING(Name, 0, 1) FROM Person GROUP BY SUBSTRING(Name, , )

which is kind of obvious from NH source code, but useless. And if I do

Projections.GroupProperty(Projections.SqlFunction(
   "SUBSTRING",
   NHibernateUtil.String,
   Projections.GroupProperty("Name"),
   Projections.GroupProperty(Projections.Constant(0)),
   Projections.GroupProperty(Projections.Constant(1))
))

then I get

SELECT SUBSTRING(Name, @p0, @p1) FROM Person GROUP BY SUBSTRING(Name, ?, ?)

where question marks seem to be some unresolved parameters, but I have no idea why.


More details:

I just found

AbstractEntityJoinWalker.InitProjection(
    SqlString projectionString,
    SqlString whereString,
    SqlString orderByString,
    string /* WTF? */ groupByString,
    SqlString havingString,
    LockMode lockMode
)

The type of groupByString looks extremely suspicious.


This should work (although you might want SUBSTRING(Name, 1, 1) but anyway):

Projections.SqlGroupProjection(
    "SUBSTRING(Name, 0, 1) as FirstChar",
    "SUBSTRING(Name, 0, 1)",
    new [] {"FirstChar"}, 
    new[] {NHibernateUtil.String}
)
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜