如何在Linq To SQL中编写此SQL查询

时间:2011-01-25 18:57:17

标签: linq-to-sql

我想知道如何在Linq中编写以下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表中没有的所有内容。

3 个答案:

答案 0 :(得分:2)


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

select * from Content where not exists(...)相同。并且在一般情况下,它优于左连接并检查null(它取决于表统计信息但是......),因为它将给出(再次,在一般情况下)半左连接而不是左连接(在执行计划中)

对于左连接本身使用如下代码(但我建议使用为您的任务生成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

答案 1 :(得分: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;

答案 2 :(得分:-1)

topicvariable =“sdfsdfsdfsdf sdfsdfsdfsdfsdfsdfsdfsd”;

var results =来自内容中的c 其中c.TopicId = topicvariable 选择c;