【问题标题】:Linq to sql double inner join statementLinq to sql 双内连接语句
【发布时间】:2014-07-14 21:58:16
【问题描述】:

我正在尝试编写一个 linq to sql 语句,它将加入总共 3 个表。表 1 = 用户(用户 ID) 表 2 = 用户课程(用户 ID,课程 ID),表 3 = 课程(课程 ID)。

这就是我想要做的:

from u in db.Users join uc in userCourse on u.userId = uc.Id
                   join c in course on uc.courseId = c.courseId

                   where u.userId = uc.userId
                   select c.name

正确的语法是什么?

【问题讨论】:

标签: sql linq-to-sql


【解决方案1】:

假设您的密钥类型匹配,您就快到了。您只需要在join 子句中使用equals 关键字即可:

from u in db.Users join uc in userCourse on u.userId equals uc.Id
                   join c in course on uc.courseId equals c.courseId   
                   where u.userId = uc.userId
                   select c.name

这是少数几个 LINQ 有点奇怪的地方之一,因为我们不能在 join 子句中使用相等运算符,但需要使用语言中其他任何地方都没有使用的关键字。这也意味着我们不能加入任意表达式。

【讨论】:

    【解决方案2】:

    试试

    from u in db.Users 
    join uc in userCourse on u.userId equals  uc.Id
    join c in course on uc.courseId equals c.courseId
    
    where u.userId = uc.userId
    select c.name
    

    也可以参考下面的链接

    https://web.archive.org/web/20101030154925/http://blogs.msdn.com/b/tikiwan/archive/2010/06/18/linq-to-sql-inner-join-left-join-examples-tutorial-samples-the-basic.aspx

    【讨论】:

      猜你喜欢
      • 2013-12-14
      • 2013-10-09
      • 2012-10-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-10-31
      相关资源
      最近更新 更多