Linq到sql!int类型的可为null的运算符

本文关键字:null 运算符 类型 sql int Linq | 更新日期: 2023-09-27 17:50:48

为空的sql列ReadershipLevels-int

level是局部int型变量

&bitwise操作员

Linq到SQL

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

如果level = 32

上面的Linq查询生成了如下的SQL:

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]

我想包括一个not,所以我做了如下

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]

它运行良好。

现在我想在LINQ中将其更改为SQL,也更改为

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

但是上面抛出的错误-不能应用运算符!到System.Nullable 类型的操作数

更改为-

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

引发错误-无法将运算符!应用于int 类型的操作数

如何在LINQ查询中添加!运算符?

Linq到sql!int类型的可为null的运算符

这将适用于您。你不需要使用&操作员

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

尝试更改:where ! (t.ReadershipLevels.Value & level) > 0
到此:where ! ((t.ReadershipLevels.Value & level) > 0 )

为什么我们需要一个按位运算符?

正如你的问题中所提到的,如果你使用这种条件,

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

它将检索中具有ReadershipLevels值的所有结果(1至31(、(64至95(、(128至159(等等

如果你真的想显示上面提到的范围内的记录,你可以使用下面的记录,因为not ([t2].[ReadershipLevels] & 32) > 0和检查它等于0是一样的,

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

或者,如果您不想显示读者级别值为"32"的记录,请执行简单的检查,如

vAdvanceSearchResults = from t 
                    in vAdvanceSearchResults 
                    where (t.ReadershipLevels ?? 0) != 32 
                    select t;

希望它能帮助