Inner Join Between Many to Many Relationship Models

倾然丶 夕夏残阳落幕 提交于 2019-12-12 01:58:51

问题


I have two model like below that are configured as many to many relationship:

public class Permission
{
    public int PermissionId { get; set; }
    public string PermissionName { get; set; }
    public virtual List<Role> Roles { get; set; }
}


public class Role
{
    public int RoleId { get; set; }
    public string Name { get; set; }
    public string ID { get; set; }
    public virtual List<Permission> Permissions { get; set; }
}

I want to do an Inner Join with Linq. I can do that easily in SQL since the join table is present there. But how can I do this with linq? Below is what I could do so far:

  from pr in Permissions
  join role in Roles on pr.Roles.Select(s => s.RoleId).FirstOrDefault() equals role.RoleId
select new { pr.PermissionName, role.RoleId } 

As you can see above the FirstOrDefault will ruin the result but other than that I cannot get to compile the query without errors.

Below is the query I am trying to write in Linq:

 SELECT P.PermissionName, R.RoleId
   FROM Permissions AS P
        INNER JOIN PermissionRoles AS PR ON P.PermissionId = PR.Permission_PermissionId
        INNER JOIN Roles AS R ON PR.Role_RoleId = R.RoleId

As you can see, an inner join is made with the join table thus query works as expected

Any help is appreciated.


回答1:


The easiest syntax is

from p in context.Permissions
from r in p.Roles // notice the p !
select new { p.PermissionName, r.RoleId, Role = r.Name, etc... }

EF will produce SQL with the required inner joins.

The fluent equivalent is

Products.SelectMany(p => p.Roles, 
                    (p, r) => new  
                              {
                                p.PermissionName, 
                                r.RoleId,
                                ...
                              })

You'll probably agree that the first form, "comprehensive syntax", wins.




回答2:


var x = from pr in Permissions
        from role in Roles
        where pr.Roles.Exists(r => r.RoleId == role.RoleId)
        select new { pr.PermissionName, role.RoleId };


来源:https://stackoverflow.com/questions/23338338/inner-join-between-many-to-many-relationship-models

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!