简体   繁体   中英

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 } . I want to return all users that have an id with either 2, 3 or 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.

update

I know why.. My code is correct. There is something wrong in the Mapper class. I used something like .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:

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.

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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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