girlcode
girlcode

Reputation: 3265

Select from multiple tables using linq

I am trying to execute the following SQL statement using linq:

SELECT TTT.SomeField
FROM Table1 as T, Table2 as TT, Table3 as TTT
WHERE (T.NumberID = 100 OR T.NumberID = 101)
  AND T.QuestionID = 200
  AND T.ResponseID = TT.ResponseID
  AND TT.AnswerID = TTT.AnswerID

Essentially getting one field from a third table based on primary/foreign key relationships to the other 2 tables. It is expected to have a single result every time.

Upvotes: 0

Views: 374

Answers (2)

Andrei
Andrei

Reputation: 56688

var query = from t in db.Table1
            join tt in db.Table2 on t.ResponseID equals tt.ResponseID
            join ttt in db.Table3 on tt.AnswerID equals ttt.AnswerID
            where (t.NumberID == 100 || t.NumberID == 101) && t.QuestionID == 200
            select ttt.SomeField

If you always expect single result, you can wrap this in ().Single(), or, if there might be no results found, in ().SingleOrDefault().

Upvotes: 2

Lucas
Lucas

Reputation: 3502

If I understand you correct. You should read something about Joins I guess. here

Upvotes: 0

Related Questions