【问题标题】:Linq == null vs IsNullOrEmpty -- Different or Same?Linq == null vs IsNullOrEmpty -- 不同还是相同?
【发布时间】:2013-09-18 05:12:13
【问题描述】:

LinqLinq to Sql 中更准确地说:以下查询中的== nullIsNullOrEmpty 之间有区别吗?

From a in context.SomeTable
where a.SomeId.Equals(SomeOtherId)
&& a.SomeOtherColumn == null
Select new .....

&

From a in context.SomeTable
where a.SomeId.Equals(SomeOtherId)
&& string.IsNullOrEmpty(a.SomeOtherColumn)
Select new .....

【问题讨论】:

  • 好吧,我不知道 linq,但 SQl Server 会将空字符串和 NUll 视为两个不同的事物(这需要两个不同的命令),而 Oracle 可能不会。所以我敢打赌,对于某些数据库,它会有所作为,而在其他数据库中则不会。

标签: c# linq linq-to-sql


【解决方案1】:

你不能在 Linq-SQL 中做String.IsNullOrEmpty

方法 'Boolean IsNullOrEmpty(System.String)' 不支持 翻译成 SQL。

如果你需要,我想你必须在你的 where 子句中同时检查 null 和 empty:

&& (a.SomeOtherColumn == null || a.SomeOtherColumn == "")

这将转换为 SQL 中的 null 和空检查。

查看其他答案,使用.Length == 0,将生成SQL 来检查varchar 列的长度,这可能比检查varchar 是否等于'' 效率低。

编辑:这是一个 Stack Overflow answer 对 SQL 的长度与空检查。看来我猜对了。

【讨论】:

    【解决方案2】:

    string.IsNullOrEmpty 也适用于空字符串,例如""

    【讨论】:

      【解决方案3】:

      最明显的区别在于名称。 IsNullOrEmpty 还会检查字符串是否为空。相当于:

      from a in context.SomeTable
      where a.SomeId.Equals(SomeOtherId)
      && (a.SomeOtherColumn == null || a.SomeOtherColumn.Length == 0)
      ...
      

      或者

      from a in context.SomeTable
      where a.SomeId.Equals(SomeOtherId)
      && (a.SomeOtherColumn == null || a.SomeOtherColumn == "")
      ...
      

      【讨论】:

        【解决方案4】:

        虽然其他答案已经表明.IsNullOrEmpty() 检查空字符串这一明显事实,但同样重要的是要注意比较

        where a.SomeOtherColumn == someNullVariable
        

        从不返回 LINQ-to-SQL 中的任何值,因为使用的是 SQL 空比较而不是 C# 空比较。 This is actually a bug in LINQ-to-SQL.

        【讨论】:

          【解决方案5】:

          IsNullOrEmpty 等于

          s == null || s.Length == 0;
          

          其中sstring 的实例

          【讨论】:

            猜你喜欢
            • 2015-06-29
            • 2018-02-28
            • 1970-01-01
            • 2011-07-18
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2012-03-28
            相关资源
            最近更新 更多