SQL Linq Many To Many

别来无恙 提交于 2021-01-29 03:05:26

问题


I have a database with a User's and Role's table. Each user can be in lots of roles, so there is a 'middle' table called UserRoles that simply contains a RoleId and UserId.

Now I need to get all the roles attached to a User.

 public IEnumerable<Role> GetAllRoles(int UserId)
    {
        var query = from R in _db.Roles
                    where RolesTbl.UserRoles.UserId == UserId
                    select R;
        return query;
    }

Now the query above doesnt work, "RolesTbl.UserRoles.UserId" I cant referance it in this way because of the Many to Many.

Anyone have a suggestion on how to resolve?


回答1:


Does this do it?

public IEnumerable<Role> GetAllRoles(int UserId)
    {
        var query = from ur IN UserRoles
                    where ur.UserId == UserId
                    select ur.Roles;
        return query;
    }



回答2:


You need to properly use a join, otherwise you'd be left with a sequence of a sequence of roles, which although you could get around by using a SelectMany, a Join is more appropriate.

public IEnumerable<Role> GetAllRoles(int userID)
{
    return _db.Roles.Join(_db.UserRoles.Where(ur => ur.UserID == userID), r => r.ID, ur => ur.RoleID, (r, ur) => r);
}

Or, if you prefer the non-fluent syntax:

public IEnumerable<Role> GetAllRoles(int userID)
{
    return from r in _db.Roles
           join ur in _db.UserRoles on r.ID == ur.RoleID
           where ur.UserID == userID
           select r;
}


来源:https://stackoverflow.com/questions/1819030/sql-linq-many-to-many

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