2011-01-25 57 views
0

我想知道如何在Linq中編寫下列SQL語句。我嘗試過,但沒有運氣。如何在Linq中編寫SQL查詢語句SQL

/*Variable*/ 
topicId = '4a31c2ee-48af-4b87-b300-112acb822ad0' 

select * from Contents c 
left join ContentToTopicRelations ctr on ctr.ContentId = c.ContentId and ctr.TopicId = topidId 
where ctr.ContentId is null 

基本上,我想獲得的所有不在ContentToTopicRelations表特定topicId內容。

回答

2

dataContext.Contents.Where(c => 
    !dataContext.ContentToTopicRelations.Any(ctr => 
    ctr.ContantId == c.ContentId && 
    ctr.TopicId == topicId)) 

它是相同的select * from Content where not exists(...)。在一般情況下,它比左連接和檢查空(它取決於表的統計信息,但..),因爲它會(一般情況下)半左連接,而不是左連接(在執行計劃中) 。

對於左連接本身使用像下面的代碼(但我建議使用代碼爲您的工作產生not exists):


from c in dataContext.Contents 
join tempCTR in dataContext.ContentToTopicRelations 
    on new { c.ContentId, topicId) equals new { tempCTR.ContentId, tempCTR.TopicId } 
    into tempCTRCollection 
    from ctr in tempCTRCollection.DefaultIfEmpty() 
where ctr == null 
select c 
+0

太好了!非常感謝。 – 2011-01-25 19:19:43

-1

topicvariable =「sdfsdfsdfsdf sdfsdfsdfsdfsdfsdfsdfsd」;

VAR結果=從C在內容 其中c.TopicId = topicvariable 選擇C;

0
topicId = '4a31c2ee-48af-4b87-b300-112acb822ad0' 

IQueryable<Content> query = 
    from c in dataContext.Contents 
    where !c.ContentToTopicRelations.Any(ctr => ctr.TopicId == topicId) 
    select c;