2010-04-03 79 views
0

我有以下SQL查詢:LINQ自參照查詢

select 
    p1.[id], 
    p1.[useraccountid], 
    p1.[subject], 
    p1.[message], 
    p1.[views], 
    p1.[parentid], 
    max(
     case 
      when p2.[created] is null then p1.[created] 
      else p2.[created] 
     end 
    ) as LastUpdate 
from forumposts p1 
    left join 
    (
     select 
      id, parentid, created 
     from 
      forumposts 
    ) p2 on p2.parentid = p1.id 
where 
    p1.[parentid] is null 
group by 
    p1.[id], 
    p1.[useraccountid], 
    p1.[subject], 
    p1.[message], 
    p1.[views], 
    p1.[parentid] 
order by LastUpdate desc 

使用下面的類:

public class ForumPost : PersistedObject 
{ 
    public int Views { get; set; } 
    public string Message { get; set; } 
    public string Subject { get; set; }   
    public ForumPost Parent { get; set; } 
    public UserAccount UserAccount { get; set; } 
    public IList<ForumPost> Replies { get; set; } 
} 

我怎麼會在複製這樣的LINQ查詢?我試過幾個變化,但我似乎無法得到正確的聯接語法。這是一個簡單的查詢是太複雜了LINQ的情況?可以使用嵌套查詢完成一些操作嗎?

查詢的目的是要找到最近更新的帖子即回覆帖子將它撞擊到列表的頂部。答覆由PARENTID列,它是自參考定義。

回答

-1

我發現NHibernate的LINQ支持不包含連接。再加上對複雜的LINQ查詢顯然缺乏經驗,我採取了以下解決方法:

  • 將修改列添加到posts表中。
  • 回覆時,更新父母的修改列以匹配回覆的創建列
  • 排序並檢索修改列的值以顯示帖子。

我認爲這是一個相當乾淨的工作,考慮到代碼的侷限性。我非常想避免不得不求助於添加另一個實體,引用一個視圖,或者僅僅使用存儲過程+數據表組合。想保留實體內的一切,只使用NHibernate的,而這種修復允許以最少的代碼氣味發生。

將此處標記爲稍後回答。

+0

真的,誰降低了6個月大的帖子,尤其是一個回答他們自己問題的帖子?至少請記下你爲什麼會被迫做這樣一件愚蠢的事情。 – Chris 2010-09-10 22:49:16

0

的左側syntaxt在LINQ連接是:

(我把它放在VB.NET):

Dim query = From table1 in myTable.AsEnumarable 'Can be a collection of your object 
      Group join table2 in MyOtherTable.AsEnumerable 
      On table1.Field(Of Type)("myfield") Equals table2.Field(Of Type)("myfield") 
      In temp 
      From table2 in temp.DefaultIsEmpty() 
      Where table1.Field(Of Type)("Myanotherfield") is Nothing 'exemple 
      Select New With { .firstField = table1.Field(Of Type)("Myanotherfield") 
           .secondField = table2.Field(Of Type)("Myanotherfield2")} 

類似的東西