Ola
Ola

Reputation: 43

Join 3 tables with a lambda expression?

I basically want the following sql query as a lambda expression:

SELECT studentname, coursename, grade
FROM student S, course C, grade G
WHERE S.id = G.studentid AND C.coursecode = G.coursecode AND G.grade<='B';

I am having trouble as I have to join 3 tables together.

Upvotes: 4

Views: 2342

Answers (1)

Jon Skeet
Jon Skeet

Reputation: 1499760

Well, that looks something like this as a query expression:

var q = from grade in db.Grades
        where grade.grade <= 'B'
        join student in db.Students on grade.studentid equals student.studentid
        join course in db.Courses on grade.coursecode equals course.coursecode
        select new { student.studentname, course.coursename, grade.grade };

(I'd normally use a variable name of query instead of q - I've just used q for formatting purposes here.)

You could translate this into explicit Join calls with lambda expressions, but I'd strongly advise you to use query expressions for complex queries like this.

Note that I've changed the order of the query to allow the "where" clause to be expressed as simply and efficiently as possible. In all likelihood a SQL query planner would optimize it anyway, but for something like LINQ to Objects this would help.

Upvotes: 5

Related Questions