简体   繁体   中英

Stuck on a part of a linq query

I have this linq query which is used with autocomplete, passing in a term it matches either email or name of user, which returns user details (UserDetails) from my database

var details = db.AspNetUsers
            .Join(db.UserDetails, 
              anu => anu.Id, ud => ud.Id, (anu, ud) => new { anu, ud })
            .Where(@t => @t.anu.Email.Contains(term) 
               || (@t.ud.firstname + @t.ud.lastname).Contains(term))
            .OrderBy(@t => @t.ud.lastname)
            .ThenBy(@t => @t.ud.firstname)
            .ThenBy(@t => @t.anu.Email)
            .Select(@t => new MemberDetails
            {
              FirstName = @t.ud.firstname,
              LastName = @t.ud.lastname,
              Email = @t.anu.Email,
              Phone = @t.ud.phone,
              Postcode = @t.ud.postcode,
              MemberNumber = @t.ud.membershipNumber,
              Street = @t.ud.street,
              City = @t.ud.city,
            }).ToList();

what I am missing is that, let's say I am the logged in user, there is a table I created called UserRoleAdmins which contains 2 columns

 - RoleId nvarchar(128)
 - UserId nvarchar(128)

RoleId is an FK to AspNetRoles table and UserId is an FK to my UserDetails table

So lets pretend we have 3 roles, red team, blue team, green team, I am the admin for the red team and the green team, so 2 records in the UserRolesAdmin table contain the red team id and my user id, and the green team id and my user id

I want to make sure that the Users I return belong to either the red team or the green team

Append this after your first where :

.Where(x => 
   db.UserRoleAdmins.Any(y => 
       x.ud.UserId == y.UserId && (y.RoleId == "red team" || y.RoleId == "green team")

Thanks to Magnus for putting me on the right direction, this is what worked, by adding an extra Where

.Where(x => db.UserRoleAdmins.Any(
  y => y.Id == userId && 
  x.anu.AspNetRoles.Select(v=>v.Id).ToList().Contains(y.RoleId)))

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