【问题标题】:Get all user for role or all roles for user获取角色的所有用户或用户的所有角色
【发布时间】:2023-03-21 04:43:02
【问题描述】:

我正在使用Identity 2EF 6,我想获取用户ID 的角色对象列表或roleId 的用户对象列表。

IEnumerable<TRole> GetUserRoles<TRole>(string userId) where TRole : class, IRole<string>

IEnumerable<TUser> GetRoleUsers<TUser>(string roleId) where TUser : class, IUser<string>

实体框架似乎没有公开TUserTRole 之间关系的链接表,因此即使使用EF 似乎也很棘手。

看起来接近高效的唯一方法是直接使用 SQL 查询数据库。

有没有人有在框架内实现这些方法的解决方案?

【问题讨论】:

    标签: asp.net entity-framework-6 asp.net-identity


    【解决方案1】:

    如果您想要实体框架解决方案,您可以使用类似 SQL 的查询表达式

    public IEnumerable<TRole> GetUserRoles<TRole>(string userId) where TRole : class, IRole<string>
    {
        return (from ur in db.Set<IdentityUserRole>()
                where ur.UserId == userId
                join r in db.Roles on ur.RoleId equals r.Id
                select r) as IEnumerable<TRole>;
    }
    
    public IEnumerable<TUser> GetRoleUsers<TUser>(string roleId) where TUser : class, IUser<string>
    {
        return (from ur in db.Set<IdentityUserRole>()
                where ur.RoleId == roleId
                join u in db.Users on ur.UserId equals u.Id
                select u) as IEnumerable<TUser>;
    }
    

    【讨论】:

      猜你喜欢
      • 2021-10-06
      • 2014-05-08
      • 2016-04-17
      • 1970-01-01
      • 2013-10-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-04-24
      相关资源
      最近更新 更多