简体   繁体   English

用lambda表达式连接3个表?

[英]Join 3 tables with a lambda expression?

I basically want the following sql query as a lambda expression: 我基本上希望以下sql查询作为lambda表达式:

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. 我遇到麻烦,因为我必须一起加入3张桌子。

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.) (我通常使用query的变量名而不是q - 我在这里仅使用q进行格式化。)

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. 可以将此转换为使用lambda表达式的显式Join调用,但我强烈建议您对这样的复杂查询使用查询表达式。

Note that I've changed the order of the query to allow the "where" clause to be expressed as simply and efficiently as possible. 请注意,我已经更改了查询的顺序,以允许“where”子句尽可能简单有效地表达。 In all likelihood a SQL query planner would optimize it anyway, but for something like LINQ to Objects this would help. 很可能SQL查询规划器无论如何都会优化它,但对于像LINQ to Objects这样的东西,这会有所帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM