LINQ to Entities:查询示例

时间:2011-05-29 20:55:08

标签: asp.net linq-to-entities entitycollection

有人可以告诉我如何在LINQ to Entities from this model中获取用户的用户组关系吗?

我需要一个列表才能以这种方式在病房后循环:

foreach (QASModel.UserGroup usergroup in ...)

如果您可以提供有关如何:

的示例,请获得积分
  • 根据用户ID
  • 获取用户的角色权限“path”
  • 根据其ID
  • 获取用户角色
  • 根据角色ID获取特定角色的所有用户 这也有帮助。

2 个答案:

答案 0 :(得分:1)

我认为这就是你要找的东西:

int uID = 55;    //The user ID that you're looking for

//Assumption for the data context name
QASDataContext ctx = new QASDataContext();   

//--(1)--
//Get the user's user groups
var user = (from u in ctx.Users
 where u.ID == uID
 select u).FirstOrDefault();

if(user != null)
{
    foreach(UserGroup in user.UserGroups)
    {
        //do your thing
    }

    //--(2)--
    //Get User's Role Permission Path(s)
    List<string> PermissionPaths = new List<string>();

    foreach(UserRole role in user.UserRoles)
    {
        foreach(UserRolesPer perPath in role.UserRolesPers)   //Can't see the whole table name
        {
            PermissionPaths.Add(perPath.Path);
        }
    }

    //You can use the PermissionPaths object now

    //--(3)--
    //Get a User's Role based on the User ID 
    //Use the same user object from above
    UserRole uRole = user.UserRole;
}

//--(4)--
//Get a all user(s) of a specific role based on the role ID
int myRoleID = 43;

var role = (from r in ctx.UserRoles
    where r.ID == myRoleID 
    select r).FirstOrDefault();

if(role != null)
{
    foreach(User u in role.Users)
    {
        // do something
    }
}

请注意,我没有通过编译器执行此操作,但这应该可以让您了解您正在寻找的内容。

答案 1 :(得分:0)

IEnumerable<UserGroup> userGroups = from ug in context.UserGroups
                                    from u in ug.Users
                                    where u.ID == [userID]
                                    select ug;

IEnumerable<string> userRoles = from ur in context.UserRoles
                                from rps in ur.UserRolesPermissions
                                where ur.UserId == id
                                select rps.Path;

IEnumerable<User> usersFromSpecificRole = from u in context.Users
                                          where u.UserRole.ID == [roleID]
                                          select u;

没有时间检查,如果有任何问题请告诉我,我会尝试修复它们。