分组用不同的选择Nhibernate

时间:2016-04-25 13:22:11

标签: c# nhibernate queryover

我想在Nhibernate QueryOver中执行此SQL查询:

SELECT id FROM tb_example
GROUP BY id, name
ORDER BY name

我尝试了什么:

1)我在.Select中添加了SelectList,试图覆盖SelectGroup的选择,但没有成功

var query = session.QueryOver<Person>()
                   .SelectList(list => list
                   .Select(p => p.Id)
                   .SelectGroup(p => p.Id)
                   .SelectGroup(p => p.Name));
query = query.OrderBy(p => p.Name).Asc;

使用query生成的SQL:

SELECT id, id, name FROM tb_example
GROUP BY id, name
ORDER BY name

2)在另一个查询的结果中使用查询。像这样:

SELECT id 
FROM 
  (SELECT id, name FROM tb_example
  GROUP BY id, name
  ORDER BY name)

但我不知道如何根据其他查询创建结果查询。

var groupByQuery = session.QueryOver<Person>()
                       .SelectList(list => list
                       .SelectGroup(p => p.Id)
                       .SelectGroup(p => p.Name));
var query = session.QueryOver<?????>();

我该怎么做?谢谢!

2 个答案:

答案 0 :(得分:0)

我知道的最简单的解决方案是:

var query = session
  .QueryOver<Person>()
  .SelectList(list => list
    .SelectGroup(p => p.Id)
    .SelectGroup(p => p.Name));
query = query.OrderBy(p => p.Name).Asc;
query.List().Select(x => (int)x[0]).ToList();

答案 1 :(得分:0)

您可以尝试以下示例

  var groupByQuery =   (from p
        in this.Session.Query<Person>()
        group p by new { Id= p.Id, Name= p.Name}
        into g
        select p).ToList();