2012-08-15 64 views
1

我正在掌握LINQ,並堅持實現查找表到對象中,然後查詢該對象(或它的關聯)的基本概念和技術。這可能是一個愚蠢的問題,可能有我自己應該做出的答案。但是我還沒有找到讓方法堅持下來的解釋。使用LINQ在查找表中查找記錄

所以我創建了一個例子DB結構,像這樣

Example Database

,我想兩個LINQ查詢第一,讓我所有的例2記錄是通過查找相關指定object1這給了我所有的例1記錄中都涉及到一個指定的對象2

第二

希望有人能踢開始我的大腦。

var examples = (from e in db.examples where e.example2.id == id).ToList(); 

SQL查詢的書面快速

SELECT * FROM [dbo].[example1] one 
JOIN [dbo].[examplelookup] lu ON one.[id] = lu.[example1id] 
JOIN [dbo].[example2] two ON lu.[example2id] = two.[id] 
WHERE one.[id] = 1 

就扼殺掉,並創造了這個我認爲應該解釋一下更

model

+1

首先,沒有愚蠢的問題。其次,請提供一些代碼:) – davenewza 2012-08-15 12:24:13

+0

都是example2和example1共享相同的鍵值? – Turbot 2012-08-15 12:32:12

+0

爲什麼不從你如何向數據庫中的數據提出問題開始 - 忽略LINQ並只考慮SQL語言,然後從那裏開始工作。 – BugFinder 2012-08-15 12:32:35

回答

2

假設

example1-> examplelookup關係名是examplelookups

example2-> examplelookup關係名是examplelookups

examplelookup - >例1的關係的名字是例1

examplelookup - >示例2的關係名稱爲example2

給出id例1

db.example1.Where(x=>x.id == id).SelectMany(x=>x.examplelookups).Select(x=>x.example2); 

,反之亦然

db.example2.Where(x=>x.id == id).SelectMany(x=>x.examplelookups).Select(x=>x.example1); 

編輯:其他更新基於格特·阿諾德的建議答案使用任何條款(這是後已經接受一個答案)

db.example1.Where(x=>x.examplelookups.Any(y=>y.example2.id == id)); 

和反之亦然

db.example2.Where(x=>x.examplelookups.Any(y=>y.example1.id == id)); 

第二編輯(再次後已接受的答案,但之後問題被改裝成包括數據模型)

db.Example1.Where(x=>x.Id == id).SelectMany(x=>x.Example2); // could have duplicates 
db.Example2.Where(x=>x.Example1.Any(y=>y.Id == id)); //alternate any form removing the duplicates 

,反之亦然

db.Example2.Where(x=>x.Id == id).SelectMany(x=>x.Example1); // could have duplicates 
db.Example1.Where(x=>x.Example2.Any(y=>y.Id == id)); //alternate any form removing the duplicates 
+0

是的,這是有道理的感謝最後我得到它 – Deviland 2012-08-15 13:04:29

+0

再次偉大的例子感謝所有你的幫助大家 – Deviland 2012-08-15 14:59:49

0

我相信什麼你正在尋找的是連接。此代碼會給你所有這一切通過連接表有相應的例題記錄例1記錄:

var x = from ex1 in example1 
     join exlookup in examplelookup on ex1.id equals exlookup.example1id 
     join ex2 in example2 on exlookup.example2id equals ex2.id 
     select ex1; 

爲了讓對面,EX2記錄,只是select ex2取代select ex1

+0

僅供參考:代碼沒有輸入到Visual Studio中,所以可能會有一個哎呀,但你應該明白了。 – 2012-08-15 12:40:36

+0

是的,我正在尋找這樣的東西,但我的域名模型有我的查找表作爲協會,現在不能像這樣訪問,(我想) – Deviland 2012-08-15 12:41:21

0

極短的時間,但儘量從開始查找表,以便您可以查詢這兩個關聯

var examples = (from el in db.examplelookup 
       where el.example2id == id 
       select el.examples1.ToList(); 

也在這裏沒有代碼檢查完成。

+0

感謝@pleun,但我無法像這樣訪問llokup表我已經添加了模型的圖像來嘗試並說明我的模型此刻的樣子。 – Deviland 2012-08-15 12:57:29

3

我知道你接受了答案,但僅僅是爲了記錄:

這是一個常見的場景中使用Any(),轉化爲一個exists在SQL。當你想example1小號指的特定example2(由id指定)做:

from ex1 in example1 
where ex1.example2s.Any(e => e.id = id) 
select ex1 

這給你example1對象的不同的列表,而與SelectMany解決方案,可能會產生與重複的列表。

+1

我已將任何解決方案併入我的答案中,並賦予您信用。另外你改變了你。奇怪,我通常首先想到任何解決方案,我必須今天有一個休息日... – 2012-08-15 13:36:05

+0

謝謝,任何時間... – 2012-08-15 13:38:58

+0

謝謝格特有得分也 – Deviland 2012-08-15 14:35:51