Search code examples
c#sql-serverlinqlinq-to-sqland-operator

Linq to sql ! operator for nullable of type int


sql column ReadershipLevels - int with null

level is local int type variable

& is bitwise operator

Linq to SQL

 vAdvanceSearchResults = from t 
                         in vAdvanceSearchResults 
                         where (t.ReadershipLevels & level) > 0 
                         select t;

if level = 32

Above Linq query generated the SQL like below:

SELECT [t2].[ReadershipLevels],[t2].[ID], [t2].[ISBN], [t2].[IsHighlighted], [t2].[Title], 
FROM (

    SELECT DISTINCT [t1].[ID], [t1].[ISBN], [t1].[IsHighlighted], [t1].[Title], [t1].[SuluAuthors], 
    FROM [dbo].[udf_SearchDWSearch]('swim', 'ALL') AS [t0]
    INNER JOIN [dbo].[DWSearch] AS [t1] ON [t0].[DWSearchID] = ([t1].[ID])
    WHERE [t1].[DatePublished] < '2016/05/27'
    ) AS [t2]
    WHERE ([t2].[ReadershipLevels] & 32) >0
    order by [t2].[ReadershipLevels]

I want to include a not So I made like below

not ([t2].[ReadershipLevels] & 32) > 0



SELECT DISTINCT [t1].[ID], [t1].[ISBN], [t1].[IsHighlighted], [t1].[Title], [t1].[SuluAuthors], 
        FROM [dbo].[udf_SearchDWSearch]('swim', 'ALL') AS [t0]
        INNER JOIN [dbo].[DWSearch] AS [t1] ON [t0].[DWSearchID] = ([t1].[ID])
        WHERE [t1].[DatePublished] < '2016/05/27'
        ) AS [t2]
        WHERE not ([t2].[ReadershipLevels] & 32) >0
        order by [t2].[ReadershipLevels]

Which is working fine.

Now I want to change same in LINQ to SQL also

vAdvanceSearchResults = from t 
                        in vAdvanceSearchResults 
                        where ! (t.ReadershipLevels & level) > 0 
                        select t;

But the above throwing error- cannot apply operator ! to operand of type System.Nullable

Changed to -

vAdvanceSearchResults = from t 
                        in vAdvanceSearchResults 
                        where ! (t.ReadershipLevels.Value & level) > 0 
                        select t;

Throwing error- Cannot apply operator ! to operand of type int

How can I add a ! operator in my LINQ query?


Solution

  • This will work for you. You don't need to use & operator

    vAdvanceSearchResults = from t 
                            in vAdvanceSearchResults 
                            where t.ReadershipLevels.Value != level && t.ReadershipLevels.Value > 0 
                            select t;