我有2個表:如何使用L2E執行此查詢?
Activities ActivityKeywords
********** ****************
ID --> ActivityID
Name Keyword
我需要返回匹配特定關鍵字的所有活動。
我有2個表:如何使用L2E執行此查詢?
Activities ActivityKeywords
********** ****************
ID --> ActivityID
Name Keyword
我需要返回匹配特定關鍵字的所有活動。
var q = from a in Context.Activities
where a.Keywords.Any(k => k.Keyword == someKeyword)
select a;
正如我在評論中說,它幾乎總是錯誤的使用LINQ加盟實體。應該使用關係屬性來代替。
結賬答案由Craig斯頓茨更清潔的方式,如果你有一個關係定義
我以前的回答是錯誤的,但這個對我的作品。
var activities = from a in db.Activities
join ak in db.ActivityKeywords on a.ID equals ak.ActivityID
where ak.Keyword == "yourkeyword"
select a;
我認爲你需要像
Give me all Activities which ID are in a list of ActivitiyKeywords.ID's
如果這是你的問題,你可以試試這個:
var ids = from k in db.ActivityKeywords select k.ActivityID;
var result = from a in db.Activities where ids.Contains(a.ID) select a;
更多信息here。
var results = (from a in Activities
from k in ActivityKeywords
where k.Keyword == "keyword" && k.ActivityID == a.ID
select a).Distinct();
這是爲什麼?你有這個信息的來源嗎? – 2009-09-01 13:41:18
因爲關係屬性是專門爲此目的而設計的。寫出一個連接就是複製你已經在(1)數據庫元數據和(2)你的實體模型中表達的代碼。每次編寫查詢時,你是否真的想重新發明這個(有時會有可能發生的錯誤)? – 2009-09-01 13:44:49
克雷格,感謝您的信息,我只開始學習EF,所以不太清楚什麼是最好的方法等。 – James 2009-09-01 14:08:06