2011-01-25 41 views
0

Linqに以下のSQLクエリを書く方法を知りたいと思います。私は頑張ったが、運がなかった。Linq to 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 

基本的に、私は特定のTOPICIDためContentToTopicRelationsテーブルに含まれていないすべての内容を取得したいと思います。

答えて

2

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

それはselect * from Content where not exists(...)と同じです。一般的には、(実行計画で)左結合の代わりに半左結合を与えるため、通常は左結合とNULLのチェック(テーブル統計に依存しますが.. ..) 。


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

グレート:左用

は、次のようなコードを使用します(私はあなたの仕事のためにnot existsを生成するコードの使用を推奨します)自体に参加!どうもありがとう。 –

-1

topicvariable = "sdfsdfsdfsdf sdfsdfsdfsdfsdfsdfsdfsd";

var results = from c inコンテンツ ここで、c.TopicId = topicvariable select 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;