c# - .Any() with Nullables - 当我期望 True 时返回 False

标签 c# linq extension-methods nullable

我有一个带有可为空 int 的 View 模型...

public ObjectViewModel (){
    public int? Total
}

...我的数据库中有几行总计为 null

尽管如此,这总是返回false:

bool exists = repo.AllRows() // renamed this for clarity; returns IQueryable
                  .Any(r => r.Total == vm.Total); // I know r.Total and vm.Total
                                                  // are both null

但以下返回 true(如预期的那样):

bool exists = repo.All().Any(r => r.Total == null);

知道我在这里做错了什么吗?

最佳答案

假设您的意思是“vm.Total is null”并且 All() 是一个拼写错误...

我认为您的问题在于将其转换为 SQL 的方式:

  • 第一个查询被翻译成带有 r.Total = @param1
  • 的 WHERE 子句
  • 第二个查询使用 IS NULL 翻译成 WHERE 子句

MSDN has a good description on NULL :

A value of NULL indicates the value is unknown. A value of NULL is different from an empty or zero value. No two null values are equal. Comparisons between two null values, or between a NULL and any other value, return unknown because the value of each NULL is unknown.

这意味着您不能在 SQL 中使用比较运算符 - 因此您也不能在 Linq to sql 中使用。

解决这个问题的一些方法是:

关于c# - .Any() with Nullables - 当我期望 True 时返回 False,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5783429/

相关文章:

c# - 为什么我可以在 Linq to XML 查询中使用 (string) 而不是 "as string"?

c# - 如何在 Linq to SQL 中合并日期时间偏移量?

c# - 解析 XML 数据时出错

swift - 检查 Swift 字典扩展中的 nil 值

C# AutoCAD 插件 SQLite - 在极少数情况下找不到错误表

c# - 用省略号截断字符串,确保不破坏任何 HTML 实体

c# - 从新节点获取符号信息

c# - Resourcemanagers 资源集有错误的值

c# - 是否有现有的 C# 扩展方法库?或分享你自己的

c# - 使用 lambda 获取扩展方法的第一个参数的属性? (x => x.请)