2011-05-29 37 views
4

加入我找到了幾個網上資源,但還沒有真正能夠這樣一個梳理NHibernate的QueryOver左外與條件

基本上我有它有兩個左outter連接的查詢就可以了

var query = session.QueryOver<NewsPost>(() => newsPostAlias) 
        .Left.JoinQueryOver(x => newsPostAlias.PostedBy,() => userAlias) 
        .Left.JoinQueryOver(x => newsPostAlias.Category,() => categoryAlias) 
         .Fetch(x => x.PostedBy).Eager 
         .Fetch(x => x.Category).Eager 
        .Where(x => !x.Deleted); 

這可能是一種無效的方式,但似乎沒有中斷。現在我想要做的是在兩個已經離開outter連接的表上,我想確保這兩個表中的Deleted列都是假的。

然而,每當我補充一點,限制居住在新聞崗位外鍵列時,結果只返回,但由於這是可空的,爲什麼我做到了左outter加入這個心不是可取的。

請告訴我基本上使其

.Where(x => !x.Deleted && !x.PostedBy.Deleted && !x.Category.Deleted); 

我看着multiqueries,期貨和析取的最好方式,我不知道應該採取什麼辦法,很明顯,我能想到的幾種方法(我的直覺告訴我的壞方法)做這件事,但最新的方法是什麼? :)

感謝

編輯 - 接受的答案修改

return session.QueryOver(() => newsPostAlias) 
        .Fetch(x => x.PostedBy).Eager 
        .Fetch(x => x.Category).Eager 
       .Left.JoinQueryOver(() => newsPostAlias.PostedBy,() => postedByAlias) 
       .Left.JoinQueryOver(() => newsPostAlias.Category,() => categoryAlias) 
       .Where(() => !newsPostAlias.Deleted) 
       .And(() => newsPostAlias.PostedBy == null || !postedByAlias.Deleted) 
       .And(() => newsPostAlias.Category == null || !categoryAlias.Deleted) 
       .OrderBy(() => newsPostAlias.PostedDate).Desc 
       .Take(10) 
       .List(); 

回答

7

我想您的查詢應該是這樣的

 Session.QueryOver<NewsPost>() 
      .Left.JoinAlias(x => x.PostedBy,() => userAlias) 
      .Left.JoinAlias(x => x.Category,() => categoryAlias) 
      .Where(x => !x.Deleted) 
      .And(x => !userAlias.Deleted) 
      .And(x => !categoryAlias.Deleted); 
+0

對不起,但通過使用。並且我確保只有已填充的PostsBy和類別的行被返回,我不能讓這個以任何其他方式工作 – Lee 2011-05-30 16:05:33

+0

糾正,我可以做到這一點這樣做。凡(()=>!newsPostAlias.Deleted) 。凡(()=> newsPostAlias.PostedBy == NULL ||(userAlias.Id ==用戶id &&!userAlias.Deleted)) 。凡( ()=> newsPostAlias.Category == null ||(categoryAlias.Id == categoryId &&!categoryAlias.Deleted)) – Lee 2011-05-30 16:08:51

0

這似乎是工作...

var posts = session.QueryOver<NewsPost>() 
    .Left.JoinAlias(x => x.Category,() => category) 
    .Left.JoinAlias(x => x.PostedBy,() => user) 
    .Where(x => x.Deleted == false) 
    .Where(Restrictions 
     .Or(
       Restrictions.Where(() => user.Deleted == false), 
       Restrictions.Where<NewsPost>(x => x.PostedBy == null) 
     ) 
    ) 
    .Where(Restrictions 
     .Or(
       Restrictions.Where(() => category.Deleted == false), 
       Restrictions.Where<NewsPost>(x => x.Category == null) 
     ) 
    ) 
    .List(); 

了這一個,你覺得會是壞的方面?如果是這樣,你能解釋一下爲什麼?我不知道有足夠的瞭解優化SQL,因此我問...

+0

謝謝這種方式也適用可愛經過一些修改(不可能做Restrictions.Where 因爲它試圖在限制的第一部分使用表格,而不是使用別名。我現在有兩種方法來實現這一點,我選擇上述答案修改,因爲我個人更喜歡使用。如果沒有限制類因爲它對我來說看起來更清潔。感謝所有的幫助,但是我認爲做一個糟糕的做法是通過在一個查詢中完成所有事情,我可以使用標準API和使用期貨來做到這一點,所以thoug它可能是最好的分裂 – Lee 2011-05-30 16:13:07

+0

酷。雖然你能不能請你提一下如何使用標準api和期貨做到這一點。期貨的優勢在於您可以在一個數據庫往返中取回多個結果集。但是你仍然需要加入,不是嗎?並不是最好讓db做它... – 2011-05-30 18:22:49