0

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

我正在尝试将此 SQL 转换为使用 EF 的扩展连接 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); 
4

2 回答 2

0

翻译 sql 查询的一种简单方法是使用LINQ 查询语法

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;

更简单,更易于阅读

于 2015-09-06T01:19:22.490 回答
0

你快到了。在加入之前尝试使用扩展方法过滤webpages_UsersInGroup集合。Where

 var q1 = db.webpages_Roles
        .Join(
        db.webpages_GroupInRoles,
        r => r.RoleId,
        gr => gr.RoleID,
        (r, gr) => r)
        .Join(
        db.webpages_UsersInGroup.Where(x=>x.UserId==1),
        ug => ug.GroupID,
        gr=>gr.GroupID,
        (ug, gr) => ug); 
于 2015-09-06T01:53:12.737 回答