David
David

Reputation: 45

Use subquery in linq query

How can I construct the below sql query in linq query to get the results ?

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

Upvotes: 0

Views: 63

Answers (2)

Saurabh Srivastava
Saurabh Srivastava

Reputation: 1113

Have a look at this article. Basically, if you want to implement SQL IN query in LINQ, you need to construct an inner query first, and then use the Contains() method. Here's my attempt:

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

Hope this will help.

Upvotes: 1

Arsalan Qaiser
Arsalan Qaiser

Reputation: 457

try this

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;  

Upvotes: 1

Related Questions