簡體   English   中英

LINQ to SQL-自連接子級到父級(同一表)

[英]LINQ to SQL - Self Join Child to Parent (Same Table)

由於某些原因,我很難全神貫注於如何執行此操作。

我有一張留言表。 (它是一個非常大的現有遺留系統的一部分,並且我無法更改表的定義方式。)只有1個帖子表。 它是一個兩級層次結構。 每個帖子都是“父母”或“孩子”。 孩子們是回復父母的職位。 (沒有其他級別。)

因此,例如,很簡單,可能會有一個Posts表,如下所示:

ID,ParentID,Content,UserID
===========================
1,0,"Hello",3
2,1,"Reply to Hello",7
3,1,"Another Reply to Hello",4
4,0,"New Post",2
...etc...

因此,假設定義了一個非常簡單的Posts表,如下所示:

INT ID [identity value for the post],
INT ParentID [0 == no parent, otherwise the value is the parent identity value]
TEXT Content [just imagine it is text]
INT UserID [the author of the post]

這是問題所在。 我想找到對特定用戶的所有回復。

因此,例如,如果我想查找對以上UserID#3的所有答復,則應提出以下建議:

ID,ParentID,Content,UserID
===========================
2,1,"Reply to Hello",7
3,1,"Another Reply to Hello",4

這是因為UserID#3發布了帖子ID#1,而這兩個是答復。

通過用戶ID#3查找所有父帖子很簡單。 我會這樣做:

var posts = (from db.Posts
  where p.UserID == 3
  && p.ParentID == 0 // this is a parent
  select p).ToList();

同樣,要查找不是由UserID#3發出的所有子級(答復)帖子,我可以這樣做:

var posts = (from db.Posts
  where p.UserID != 3
  && p.ParentID != 0 // this is a child
  select p).ToList();

但是,如何找到僅對UserID#3的所有回復?

想象一下,Posts表在過去10年中有1,000,000行,並且可能只有3行是答復,因此我不能完全將所有表都粗暴地放入某個List中,然后進行排序。 我需要執行1 LINQ to SQL查詢,僅返回所需的3行。

如果我可以這樣做,它將起作用:

int userId = 3;
var posts = (from p in db.Posts
  where p.UserID != 3
  && p.ParentID != 0 // this is a child
  && DID_USER_CREATE_POST(userId,p.ID) // can't do this -- since this imaginary C# function won't work here
  select p).ToList();

我想我需要做一些自連接(???),因為父級和子級都在同一個表中,以得出這3個需要的行..但是我還沒有弄清楚如何做到這一點。現有的表格結構。

有誰知道我如何使用LINQ to SQL做到這一點。 我正在使用C#,代碼將在ASP.NET MVC控制器(發出RSS)中。

感謝您的協助!

我沒有像您一樣針對數據結構嘗試過此操作,但它可能使您到達那里:

var id = 3;
var query =
from p in db.Posts
join r in db.Posts on p.ID equals r.ParentId
where p.UserId == id && p.ParentId == 0
select new { Post = p, Reply = r};

如果您具有正確的外鍵設置,則LINQ應該會看到引用,因此您的查詢將是這樣的。

var posts = from p in db.Posts
  where p.Parent != null //Looking for children only
  && p.Parent.UserId == 3 //UserId of the parent post

引用對象的名稱可能有所不同。 如果看不到任何此類對象,則也可以通過join實現相同的目的。

from post in db.Posts
join parent in db.Posts on post.ParentId equals parent.ID
where parent.UserId == 3
select post

我省略了其他更簡單的where子句。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM