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?
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>;
}