public IActionResult Login( UserDto dto)
{
try
{
var roleName = (from r in _context.Roles
join u in _context.Users on r.UserId equals u.UserId
where u.UserId == dto.UserId
select r.RoleName).FirstOrDefault();
if (roleName != null)
{
// Set the RoleName in the session
HttpContext.Session.SetString("Role", roleName);
}
我正在尝试获取用户 ID 上的角色名称并在角色名称上设置会话
在asp.net core Identity中,数据库有User表、User-Role表和Role表。如果您正在处理相同的结构,您应该同时加入 User-Role 表,那么 linq 应类似于:
var query = from user in _context.Users
join userRole in _context.UserRoles on user.Id equals userRole.UserId
join role in _context.Roles on userRole.RoleId equals role.Id
where user.Id == "userId"
select new
{
UserId = user.Id,
UserName = user.UserName,
RoleId = role.Id,
RoleName = role.Name
};
var roleName = query.FirstOrDefault();
如果您正在进行没有用户角色表的自定义设计,您应该查询用户表并加入角色表,然后查询应类似于
var roleName = (from u in _context.Users
join r in _context.Roles on r.UserId equals r.UserId
where u.UserId == dto.UserId
select r.RoleName).FirstOrDefault();
如果无法获取角色名称,需要先确定该用户和角色是否存在,以及该用户是否已经在数据库中附加了该角色。