Can LINQ (to SQL) execute bitwise queries?

I have a user table that includes the bitmask of the roles the user belongs to. I would like to select users belonging to one or more roles in the bitmask. For instance:

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

This selects all users who have the roles "2", "4" or "16" in their bitmask. Can this be expressed in a LINQ query? Thanks.

+4
source share
3 answers

I think this will work, but I have not tested it. Create the name of your DataContext. YMMV.

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

As a side note, though for my fellow googlers: UserRolesBitmask | 22 == 22 UserRolesBitmask | 22 == 22 selects all users who have no other flags (this is not a filter, as 1==1 say).

You also want:

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

If this does not work, you can always use ExecuteCommand :

 DataContext.ExecuteCommand("select * from [User] where UserRolesBitmask | {0} = {0}", 22); 
0
source

Source: https://habr.com/ru/post/1277134/