Ado.net Entity Framework 中的多对多查询
这个弄了好久。。。倒头来发现自己钻牛角尖了,把方法记了下:
这是一个权限管理例子,有用户表,权限表,角色表 ,由于是多对多关系,它们都有个中间表
用户和角色的关系是:N:N
角色和权限的关系是:N:N
Linq To Entities中,当我要查询出“指定的用户是否拥有某个权限”时:
代码:
//初始化
var marine_user = this.Database.GetQueryable<marine_User>();
var marine_role = this.Database.GetQueryable<marine_Role>();
var marine_permission = this.Database.GetQueryable<marine_Permission>();
//查询出拥有指定权限的角色列表
var queryRole = from p in marine_permission
from r in marine_role
from rp in r.marine_Permission
where rp.PermissionID == p.PermissionID && p.Namepace + "." + p.Controller + "." + p.Action + "," + p.Assembly == actionName
select r;
//查询出拥有 queryRole 角色的用户列表
var queryUser = from u in marine_user
from r in queryRole
from ur in u.marine_Role
where ur.RoleID == r.RoleID
select u;
var marine_user = this.Database.GetQueryable<marine_User>();
var marine_role = this.Database.GetQueryable<marine_Role>();
var marine_permission = this.Database.GetQueryable<marine_Permission>();
//查询出拥有指定权限的角色列表
var queryRole = from p in marine_permission
from r in marine_role
from rp in r.marine_Permission
where rp.PermissionID == p.PermissionID && p.Namepace + "." + p.Controller + "." + p.Action + "," + p.Assembly == actionName
select r;
//查询出拥有 queryRole 角色的用户列表
var queryUser = from u in marine_user
from r in queryRole
from ur in u.marine_Role
where ur.RoleID == r.RoleID
select u;