简体   繁体   English

返回列表中所有具有角色ID的用户

[英]Return all users with role id in a list

I have 3 tables: User, Roles, and UserRoles and I have a list of roles ids { 2, 3, 4 } . 我有3个表:User,Roles和UserRoles,并且具有角色ID { 2, 3, 4 } I want to return all users that have an id with either 2, 3 or 4. 我想返回ID为2、3或4的所有用户。

Models: 楷模:

public partial class User
{
    public int Id { get; set; }
    public virtual ICollection<UserRoles> UserRoles { get; set; }
}

public partial class Roles
{
    public int Id { get; set; }
}

public partial class UserRoles
{
    public int UserId { get; set; }
    public int RoleId { get; set; }

    public virtual Users Users { get; set; }
    public virtual Roles Roles { get; set; }
}

And the code I have: 和我有的代码:

int[] RoleIds = { 2, 3, 4 };
return await _dbContext.Users
    .Where(u => u.UserRoles.Any(x=> RoleIds.Contains(x.RoleId)));

I don't know why but my result contains records with roleId == 1. 我不知道为什么,但是我的结果包含具有roleId == 1的记录。

update 更新

I know why.. My code is correct. 我知道为什么。我的代码是正确的。 There is something wrong in the Mapper class. Mapper类中有问题。 I used something like .FirstOrDefault().RoleId. 我使用了诸如.FirstOrDefault()。RoleId之类的东西。 so it only returns the first data, and a user may have multiple roles! 因此它仅返回第一个数据,并且用户可能具有多个角色! Thank you guys 感谢大伙们

try going backwards and see if that helps... 尝试倒退,看看是否有帮助...

return await _dbContext.UserRoles
     .Where(r => RoleIds.Contains(r.RoleId))
     .Select(r => r.Users)

If you don't want to add navigational properties to User nor to Roles , you can do this easily using LINQ query syntax: 如果您不想将导航属性添加到UserRoles ,则可以使用LINQ查询语法轻松地做到这一点:

var usersQuery = from role in _dbContext.Roles
                 join userRole in _dbContext.UserRoles 
                     on role.Id equals userRole.RoleId
                 join user in _dbContext.Users
                     on userRole.UserId equals user.Id;
                 where roleIds.Contains(role.Id)
                 select user;

var users = usersQuery.ToList();

Sounds like you're trying to get the User from the UserRole relationship table. 听起来您正在尝试从UserRole关系表中获取用户。

Here's how to do it in query expression syntax: 以下是使用查询表达式语法的方法:

int[] RoleIds = { 2, 3, 4 }; 

var users = from ur in _dbContext.UserRoles
            where RoleIds.Contains(ur.RoleId)
            select ur.Users;

Or if you don't want or have navigational properties: 或者,如果您不想要或没有导航属性:

int[] RoleIds = { 2, 3, 4 }; 

var users = from ur in _dbContext.UserRoles
            where RoleIds.Contains(ur.RoleId)
            join user in _dbContext.Users
            on ur.UserId equals user.Id
            select user;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM