在 linq 查询中使用子查询

Use subquery in linq query

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

SELECT PageNumber from LMS_SurveyQuestion WHERE SurveyQuestionID IN
(SELECT  SurveyQuestionID from LMS_SurveyQuestionOptionChoice 
WHERE NextPageNumber = 4) and SurveyID = 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;  

看看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);

希望这会有所帮助。