如何扩展连接不同ID上的3个表

时间:2015-09-05 23:21:10

标签: sql-server entity-framework inner-join linq-extensions

SQL内连接查询:

 Select 
     r.RoleName 
 From 
     webpages_Roles r 
 Inner Join 
     webpages_GroupInRoles gr ON r.RoleID = gr.RoleId 
 Inner Join 
     webpages_UsersInGroup ug ON gr.GroupID = ug.GroupID 
 Where 
     ug.UserID = 1

我正在尝试使用EF将此SQL转换为扩展连接3表:

var q1 = db.webpages_Roles
    .Join(db.webpages_GroupInRoles,
          r => r.RoleId,
          gr => gr.RoleID,
          (r, gr) => r)
    .Join(db.webpages_UsersInGroup,
          ug => ug.GroupID,
          gr=>gr.GroupID,
          (ug, gr) => ug); 

2 个答案:

答案 0 :(得分:0)

翻译SQL查询的简便方法是使用LINQ query syntax

var query= from r in db.webpages_Roles
           join gr in db.webpages_GroupInRoles on r.RoleID equals gr.RoleId
           join ug in db.webpages_UsersInGroup on gr.GroupID equals ug.GroupID 
           where ug.UserID == 1
           select r.RoleName;

更简单易读

答案 1 :(得分:0)

你几乎就在那里。在加入之前,尝试使用pip install twisted扩展方法过滤webpages_UsersInGroup集合。

Where