在linq查询中使用子查询

时间:2017-02-10 06:33:27

标签: c# .net linq linq-to-entities

如何在linq查询中构造以下sql查询以获得结果?

SELECT PageNumber from LMS_SurveyQuestion WHERE SurveyQuestionID IN
(SELECT  SurveyQuestionID from LMS_SurveyQuestionOptionChoice 
WHERE NextPageNumber = 4) and SurveyID = 1

2 个答案:

答案 0 :(得分:1)

试试这个

var result = from l in LMS_SurveyQuestion 
             let lsq = from l_S in LMS_SurveyQuestionOptionChoice 
             where l_S.NextPageNumber = 4
             select l_S.SurveyQuestionID 
             where lsq.Contains(l.SurveyQuestionID) and l.surveyid = 1
             select l.PageNumber;  

答案 1 :(得分:1)

看看this article。基本上,如果要在LINQ中实现SQL IN查询,则需要首先构造内部查询,然后使用Contains()方法。这是我的尝试:

var innerQuery = (from log in LMS_SurveyQuestionOptionChoice where log.NextPageNumber = 4 select log.SurveyQuestionID);

var result = (from f in LMS_SurveyQuestion where innerQuery.Contains(f.SurveyQuestionID) && f.SurveyID = 1 select f);

希望这会有所帮助。