2010-02-23 89 views
2

如果我的Table3有一個FK指向Table2,它有一個指向Table1的FK,我通過intellisense看到的是我可以參考表3中的表2,但是我不能去表3 .Table2.Table1只有一層深。LINQ查詢中的多層外鍵

from t3 in Table3 
where t3.t2.property == "some value" && t3.t2.t1.property == "some other value" 
select t3.t2.t1; 

這是什麼esentially我想做的事,但我只能引用T2,但並不表明T2已經鏈接到T1。

我應該這樣做:

from t3 in Table3 
from t1 in Table1 
where t3.t2.property == "some value" && t1.property == "some other value" 
select t1; 

回答

3

你可以加入所有表:

from t3 in Table3 
join t2 in Table2 on t3.Table2_FK equals t2.ID 
join t1 in Table1 on T2.Table1_FK equals t1.ID 
where t2.property == "some value" && t1.property == "some other value" 
select t1; 

(編輯)

我不會去只是一個層次深度。事實上,你的第一個例子應該工作。當然,你的關係必須是N到1:

Table3 (n) --- (1) Table2 (n) --- (1) Table1 

給出的Table3你可以做t3

t3.Table2.Table1 

你有在.dbml文件Table2Table1之間的正確連接?

+0

我認爲我展示的第二種方式做同樣的事情,因爲LINQ to SQL已經知道FK關係。那是不正確的? – jamone 2010-02-23 13:51:59

+0

據我所知,我確實有Table3(n)---(1)Table2(n)---(1)Table1的設置。我能做t3.t2和t2.t1的事實不應該獨立表明這種關係是正確的? – jamone 2010-02-23 14:37:31

+0

啊,我不知道爲什麼它沒有咬我之前。 Table2和Table1之間的鏈接被顛倒過來。它是表2(1)---(n)表1。 – jamone 2010-02-23 14:42:46