NHibernate QueryOver Having子句

时间:2011-06-15 13:57:38

标签: nhibernate queryover

我想用QueryOver编写这样的查询,以便结果SQL类似于以下内容:

Select Bar, count(*) from Foo group by Bar having count(*) > 1

我该怎么做?

2 个答案:

答案 0 :(得分:7)

我认为你只会使用Where方法

Session.QueryOver<Foo>()
    .Select(Projections.GroupProperty(Projections.Property<Foo>(foo => foo.Bar)),
            Projections.Count<Foo>(f => f.Id))
    .Where(Restrictions.Gt(Projections.Count<Foo>(f => f.Id), 1));

答案 1 :(得分:3)

Vadim的答案是正确的,只是想提一下,如果需要检查另一个数据库字段的“拥有”条件,这可能是一个挑战。

例如以下SQL:

select Foo.Bar, COUNT(*) from Foo
group by Foo.Bar
having Foo.Bar <> COUNT(*)

应该基本上使用QueryOver创建:

Session.QueryOver<Foo>()
    .Select(Projections.GroupProperty(Projections.Property<Foo>(foo => foo.Bar)),
            Projections.Count<Foo>(f => f.Id))
    .Where(Restrictions.NotEqProperty(Projections.Count<Foo>(f => f.Id), Projections.Property<Foo>(foo => foo.Bar)));

但不幸的是,NHibernate产生了以下无效 SQL(使用where而不是):

    select Foo.Bar, COUNT(*) from Foo
    group by Foo.Bar
    where Foo.Bar <> COUNT(*)

要解决这个问题,我必须创建以下继承:

    public class NonEqPropertyExpression : EqPropertyExpression
    {
        public NonEqPropertyExpression(IProjection lhsProjection, IProjection rhsProjection)
            : base(lhsProjection, rhsProjection)
        {
        }

        protected override string Op
        {
            get { return "<>"; }
        }
    }

并使用我的新类而不是标准的NonEqProperty:

Session.QueryOver<Foo>()
    .Select(Projections.GroupProperty(Projections.Property<Foo>(foo => foo.Bar)),
            Projections.Count<Foo>(f => f.Id))
    .Where(new NonEqPropertyExpression(Projections.Count<Foo>(f => f.Id), Projections.Property<Foo>(foo => foo.Bar)));

在这种情况下,生成的SQL是正确的。