2012-04-17 91 views
0

我對NHibernate很新。我使用CreateSQLQuery編寫了這個代碼,但是如果可能的話我想把它移到NHibernate Criteria格式。我的查詢是這樣的:左外連接的複雜NHibernate標準?

select parent.ID as Id, ValueA.Total as ValueACount, ValueB.Total as ValueBCount 
from ParentTable parent 
left outer join 
(
    select count(*) as Total, ID 
    from ChildTable 
    where state = 'ValueA' 
    group by ID 
) ValueA on ValueA.ID = parent.ID 
left outer join 
(
    select count(*) as Total, ID 
    from ChildTable 
    where state = 'ValueB' 
    group by ID 
) ValueB on ValueB.ID = parent.ID 

我改變了表名/值來抽象一下。代碼按原樣運行,但這是我們在整個解決方案中唯一的查詢。我想看看我們是否可以擺脫它。

提前感謝所有可以幫助的人。如果你想給我一個能夠幫助我的非常好的網頁的鏈接,那也沒關係。我會至少大拇指:)

我也見過類似的問題。如果你覺得其他一些問題/答案會對我有很大的幫助,請隨時指出我的意見。

回答

2

,你可以嘗試一些LINQ福

var results = from p in session.Query<Parent>() 
       select new 
       { 
        p.Id, 
        ValueACount = (from c1 in session.Query<Child>() where c1.State == "ValueA" && c1.Parent == p select c1).Count(), 
        ValueBCount = (from c2 in session.Query<Child>() where c2.State == "ValueB" && c2.Parent == p select c2).Count(), 
       }; 

或使用標準

var results = session.CreateCriteria<Parent>("p") 
    .SetProjection(Projections.ProjectionList() 
     .Add(Projections.Property("Id")) 
     .Add(Projections.SubQuery(DetachedCriteria.For<Child>() 
      .Add(Restrictions.Eq("State", "ValueA") && Restrictions.EqProperty("Parent", "p")) 
      .SetProjection(Projections.RowCount()))) 
     .Add(Projections.SubQuery(DetachedCriteria.For<Child>() 
      .Add(Restrictions.Eq("State", "ValueB") && Restrictions.EqProperty("Parent", "p")) 
      .SetProjection(Projections.RowCount())))) 
    .List(); 
+0

我想出來的第二件事情現在。似乎回來沒有結果。不知道有什麼問題。無論是你的代碼是錯誤的還是我重新翻譯成我的課程。我的課程不匹配字段與表格。然後,我用一些必要的屬性製作了一些虛擬類,但無濟於事。這沒有用。不過,我注意到了你的代碼。你有「Restrictions.EqProperty('Parent','p'))。那些應該是屬性名稱?即」Id「,」Id「? – vbullinger 2012-04-18 16:11:56

+0

我認爲id是類中的一對多關聯。我的代碼應該模仿sql'Select id,(從c1中選擇Count(*),其中c1.parentId == p.id和c1.state =「valueA」)從父p' – Firo 2012-04-18 19:45:15

+0

我認爲EqProperty測試,如果右側的值是等於左側...參數的標題爲lhs和rhs,在NHibernate的元數據...你似乎將它們標記爲表名稱和別名我是否誤解? – vbullinger 2012-04-19 23:13:42