从 GroupBy 键中选择一个对象

Selecting an object from the GroupBy key

我习惯于 GroupBy() 与其说是一门科学,不如说是一门艺术,但也许有人可以帮助我解决一个非常具体的问题:

给定以下代码

var results = session.Query<MyClass>()
.GroupBy(c => c.OtherPersistentObject)
.Select(group => new
{
    key = group.Key,
    count = group.Count()
})
.ToList();

生成的查询结果是这样的:

    /* [expression] */select
    otherclass_.ID as col_0_0_,
    cast(count(*) as INT) as col_1_0_,
    otherclass_.ID as id1_1_,
    otherclass_.START_DATE as start2_1_,
    otherclass_.END_DATE as end3_1_,
    otherclass_.Zone as zone9_1_
from
    mytable mytable0_ 
left outer join
    otherclass otherclass_ 
        on mytable0_.otherID=otherclass_.ID 
group by
    mytable0_.otherID

这给了我 SQL 错误“Column 'otherclass .ID' is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause

有没有办法让 Select 做我想做的事?

TIA

试试这个:

var results = session
    .Query<MyClass>()
    .GroupBy(c => c.OtherPersistentObject)
    .Select(group => new
    {
        key = group.Key.Id,
        count = group.Count()
    })
    .ToList();

Here您可以找到错误的原因。

这是一个已知的 NHibernate 问题 NH-3027

作为解决方法,您可以使用此 中描述的最后一种方法(将 GroupBy 部分重写为子查询)。所以您的查询可以重写为:

var results = session.Query<MyClass>()
        .Where(c => c == session.Query<MyClass>().First(cs => cs.OtherPersistentObject == c.OtherPersistentObject))
        .Select(x => new
        {
            key = x.OtherPersistentObject, 
            count = session.Query<MyClass>().Count(cs => cs.OtherPersistentObject == x.OtherPersistentObject)
        }).ToList();