Get all user for role or all roles for user

asp.net asp.net-identity entity-framework-6

Question

I am using Identity 2 and EF 6 and I would like to get a list of role objects for a user id or a list of user object for a roleId.

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

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

Entity framework does not appear to expose the linking table for the relationship between TUser and TRole so even using EF seems tricky.

It looks like the only way to do it close to efficiently is to query the database directly using SQL.

Does anyone have a solution to implementing these methods within the frameworks?

1
1
7/19/2016 3:42:58 AM

Accepted Answer

If you want Entity Framework solution you can use SQL-like query expressions

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>;
}
2
7/19/2016 7:13:32 AM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow