Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can LINQ (to SQL) do bitwise queries?

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.

like image 718
Nick Avatar asked Sep 24 '08 23:09

Nick


People also ask

Is LINQ to SQL obsolete?

LINQ to SQL was the first object-relational mapping technology released by Microsoft. It works well in basic scenarios and continues to be supported in Visual Studio, but it's no longer under active development.

How does a LINQ query transform to a SQL query?

LINQ to SQL translates the queries you write into equivalent SQL queries and sends them to the server for processing. More specifically, your application uses the LINQ to SQL API to request query execution. The LINQ to SQL provider then transforms the query into SQL text and delegates execution to the ADO provider.

What kind of data can be queried with LINQ?

LINQ offers common syntax for querying any type of data source; for example, you can query an XML document in the same way as you query a SQL database, an ADO.NET dataset, an in-memory collection, or any other remote or local data source that you have chosen to connect to and access by using LINQ.

Which entities can LINQ use to perform queries?

LINQ to Entities queries are comprised of LINQ standard query operators (such as Select, Where, and GroupBy) and expressions (x > 10, Contact. LastName, and so on). LINQ operators are not defined by a class, but rather are methods on a class.


2 Answers

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
like image 64
Eric Avatar answered Sep 28 '22 02:09

Eric


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
like image 21
KevDog Avatar answered Sep 28 '22 02:09

KevDog