Question

I have a table of Users that includes a bitmask of roles that the user belongs to. I'd like to select users that belong to one or more of the roles in a bitmask value. For example:

select *
from   [User]
where  UserRolesBitmask | 22 = 22

This selects all users that have the roles '2', '4' or '16' in their bitmask. Is this possible to express this in a LINQ query? Thanks.

Was it helpful?

Solution

I think this will work, but I haven't tested it.Substitute the name of your DataContext object. YMMV.

from u in DataContext.Users
where UserRolesBitmask | 22 == 22
select u

OTHER TIPS

As a side note though for my fellow googlers: UserRolesBitmask | 22 == 22 selects all users that don't have any other flags (its not a filter, its like saying 1==1).

What you want is either:

  • UserRolesBitmask & 22 == 22 which selects users which have all the roles in their bitmask or:
  • UserRolesBitmask & 22 != 0 which selects users which have at least one of the roles in their bitmask

If that doesn't work you could always use ExecuteCommand:

DataContext.ExecuteCommand("select * from [User] where UserRolesBitmask | {0} = {0}", 22);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top