LinQ to Entities:查询五个表JOIN

时间:2011-06-16 04:41:54

标签: c# sql linq-to-entities

我有五个表都带有ID

的主键
  • 用户
  • User_Role_Relation with Foreign Keys User_ID和Role_ID
  • 作用
  • Role_Right_Relation with Foreign Keys Role_ID和Right_ID
  • 右键

我目前正在使用存储过程中的以下查询获取所选用户的权限

  SELECT DISTINCT 
      tbl_Right.ID, tbl_Right.Name    
  FROM 
      tbl_User_Role_Relation 
  INNER JOIN 
      tbl_Role_Right_Relation ON tbl_User_Role_Relation.Role_ID =  tbl_Role_Right_Relation.Role_ID 
  INNER JOIN 
      tbl_Right ON tbl_Role_Right_Relation.Right_ID = tbl_Right.ID
  WHERE 
      tbl_User_Role_Relation.User_ID = @User_ID

我试图用这段代码将其转换为LINQ to Entity

var query = from r in context.Rights
            from rrr in r.Role_Right_Relation
            from rl in rrr.Role
            from urr in rl.User_Role_Relation
            where urr.User_ID == userid
            select r;

但是我收到以下错误

  

源类型为“System.Linq.IQueryable”的查询表达式中的后续from子句中不允许使用类型为“Models.Role”的表达式在调用“SelectMany”时类型推断失败

任何建议都会有所帮助。

感谢。

3 个答案:

答案 0 :(得分:2)

首先,linq查询正在进行交叉连接,而不是像sql那样的内部连接。你应该看看this

其次,您可能最好正确定义edmx中实体之间的关系,您可能根本不需要加入,而是可以使用navigation properites访问父/子并过滤那些属性直接

实体框架的想法是你不必平铺层次结构

答案 1 :(得分:0)

编辑3

如果您逐字发布了代码,那么您就错过了一行

from u in urr.Users

所以:

var query = from r in context.Rights
from rrr in r.Role_Right_Relation
from rl in rrr.Role
from urr in rl.User_Role_Relation
from u in urr.Users
where u.User_ID == userid
select r;

或者至少有一个拼写错误,应该在哪里阅读:

where urr.User_ID == userid

导致:

var query = from r in context.Rights
from rrr in r.Role_Right_Relation
from rl in rrr.Role
from urr in rl.User_Role_Relation
where urr.User_ID == userid
select r;

答案 2 :(得分:0)

如果您使用方法语法,您应该能够执行以下操作:

var user = context.Users.FirstOrDefault(u => u.Id == userId);
var rights =user.Roles.SelectMany(role => role.Rights).Distinct();

在获得权利之前,请务必检查用户是否为空

相关问题