NHibernate SQLFunction group by

时间:2014-04-27 23:51:33

标签: c# mysql nhibernate group-by queryover

我正在尝试做这样的事情:

SELECT round(song.rating), count(song.song_id) FROM song
GROUP BY round(song.rating);

我的QueryOver:

 var output = sess.QueryOver<song>()
                .SelectList(list => list
                    .Select(Projections.SqlFunction("round", NHibernateUtil.Int32, Projections.GroupProperty("rating")))
                    .SelectCount(s => s.song_id))
                .List<object[]>()
                .Select(prop => new RatingStat
                {
                    rating = (int)prop[0],
                    count = (int)prop[1]
                }).ToList<RatingStat>();

预期产出:

+---------------------------+---------------------------+
|                         0 |                        12 |
|                         1 |                         1 |
|                         3 |                         1 |
|                         4 |                         6 |
|                         5 |                         3 |
|                         6 |                         6 |
|                         7 |                        12 |
|                         8 |                         7 |
|                         9 |                         9 |
|                        10 |                         2 |
+---------------------------+---------------------------+

实际输出:

0                         12
1                         1
3                         1
4                         1
4                         3
4                         1
4                         1
5                         1
5                         1
5                         1
6                         2
6                         1
6                         3
7                         2
7                         9
7                         1
8                         1
8                         3
8                         2
8                         1
9                         1
9                         3
9                         1
9                         4
10                        2

我使用自己继承自MySQL5Dialect的方言,因为我的MySQL方言不支持round函数。 以下是我的方言中定义圆函数的方法:

 RegisterFunction("round", new StandardSafeSQLFunction("round", NHibernateUtil.Int32,1));

我的问题是,为什么我有多个具有相同评级值的组?圆形值应该是不同的。圆函数是否可能无法正常工作? 编辑:添加了基本的SQL语句

 SELECT round(this_.rating) as y0_, count(this_.song_ID) as y1_ FROM song this_ GROUP BY this_.rating

1 个答案:

答案 0 :(得分:3)

找到解决方案:

 var t = Projections.SqlFunction("round", NHibernateUtil.Int32, Projections.GroupProperty("rating"));
 var output = sess.QueryOver<Song>()
       .SelectList(list => list
       .Select(Projections.SqlFunction("round", NHibernateUtil.Int32, Projections.GroupProperty(t)))
       .SelectCount(s => s.song_id))
       .List<object[]>()
       .Select(prop => new RatingStat
        {
            rating = (int)prop[0],
            count = (int)prop[1]
        }).ToList<RatingStat>();