I've created a user and attached to him a role that has a number of claims. The problem is I don't see a direct way to access retrieve them using Entity Framework Core and Identity integration. Here's what I'd like to do ideally:
return _context.Users .Include(u => u.Roles) .ThenInclude(r => r.Role) .ThenInclude(r => r.Claims)
But there's not Role property, just RoleId. So I can not Include role claims. Of course I get make a separate query to get claims or even use RoleManager:
var user = _context.Users.Single(x => x.Id == ...); var role = _roleManager.Roles.Single(x => x.Id == user.Roles.ElementAt(0).RoleId); var claims = _roleManager.GetClaimsAsync(role).Result;
but it looks inefficient and even ugly. There should be a way to make a single query.
My last hope was Controller.User property (ClaimsIdentity). I hoped it somehow smartly aggregates claims from all the roles. But seems like it doesn't...
You can use SQL-like query expressions and get all claims from all roles of a user like this:
var claims = from ur in _context.UserRoles where ur.UserId == "user_id" join r in _context.Roles on ur.RoleId equals r.Id join rc in _context.RoleClaims on r.Id equals rc.RoleId select rc;