2011-06-15 103 views

回答

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

應該是'Projections.GroupProperty(Projections.Property (foo => foo.Bar))' – 2011-06-15 15:02:36

+0

@David,你就是這樣,改了。 – Vadim 2011-06-15 15:36:23

+0

如果我們使用Projections.Sum(),這裏有什麼區別? – Ammad 2015-04-10 16:31:40

3

從瓦迪姆的答案是正確的,只是想提一提,它可能是一個挑戰,如果一個需要檢查「具有」狀態對另一數據庫領域。

例如以下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(使用,其中,代替具有) :

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是正確的。

+0

我有類似的問題張貼在問題。沒有得到另一個數據庫,但標準出現在哪裏,而不是有。你可以請看看http://stackoverflow.com/questions/29565783/nhibernate-queryover-criteria-appearing-in-where-instead-in-having-clause-err – Ammad 2015-04-10 16:36:36