实体框架Linq查询多对多关系?

时间:2016-08-09 17:38:43

标签: c# sql entity-framework linq linq-to-entities

我有以下型号:

public class ApplicationUser : IdentityUser<string, ApplicationUserLogin, ApplicationUserRole, ApplicationUserClaim>
{
    public bool HasPermission(string permission)
    {
        return Roles.Any(r => r.Role.Permissions
                  .Any(p => p.Name == permission));
    }
    // Some other Stuff

}

public class ApplicationRole : IdentityRole<string, ApplicationUserRole>
{
    public ApplicationRole(string name) : this()
    {
        this.Name = name;
    }

    public virtual ICollection<Permission> Permissions { get; set; }
 }

public class ApplicationUserRole : IdentityUserRole
{
    public ApplicationUserRole(): base() { }

    public virtual ApplicationRole Role { get; set; }
}

public class Permission
{
    public byte Id { get; set; }
    public string Name { get; set; }

    public virtual ICollection<ApplicationRole> Roles { get; set; }
}

基本上它们映射到五个表:Users,Roles,UserRoles,Permissions和RolePermissions - 目前我没有RolePermission的模型 - 我需要一个吗?

我希望使用带有lambda表达式的linq获取给定用户的权限列表,类似于以下SQL:

Select p.Id, p.Name 
From Permission p
inner join RolePermission rp on rp.PermissionId = p.Id
inner join UserRole ur on ur.RoleId = rp.RoleId 
where ur.UserId = 'xyz' 

我不确定我从哪个实体开始使用LINQ获取权限列表 - 我只能设法使用以下内容获取角色?

var permissions =  _context.Users.Where(u => u.Id == userId)
                               .SelectMany(r => r.Roles.SelectMany(p => p.Role.Permissions))
                               .ToList();

有什么想法吗?

2 个答案:

答案 0 :(得分:0)

要在Linq中加入,你可以使用类似的东西。

var permissions = new List<Permission>(){ 
                  new Permission (){
                                      Id= 1, 
                                      Name = "Test1"
                                   }, 
                  new Permission{     Id = 2, 
                                      Name = "Test2"}
};
var applicationRoles = new List<ApplicationRole>(){
                       new ApplicationRole{ 
                                            Id =1, 
                                            PermissionId = 2
    }};

var x = from p in permissions
        join ar in applicationRoles on p.Id equals ar.PermissionId
        select p;


public class Permission{
public byte Id {get;set;}
public string Name {get;set;}

public List<ApplicationRole> Roles {get;set;}
}


public class ApplicationRole {
public byte Id {get;set;}   
public byte PermissionId {get;set;}
}

我不确定这是不是你真正要问的,所以我希望它可以帮到你。

答案 1 :(得分:0)

管理如下:

var permissions =  _context.Users.Where(u => u.Id == userId)
                           .SelectMany(r => r.Roles.SelectMany(p => p.Role.Permissions)).Distinct().ToList();