我有一个带有可为空 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 中使用。
解决这个问题的一些方法是:
- 在选择要使用的查询形式之前测试 vm.Total 中的 null。
- 使用
Object.Equals
进行比较 - 有关详细信息,请参阅此博客文章 - http://www.brentlamborn.com/post/LINQ-to-SQL-Null-check-in-Where-Clause.aspx
关于c# - .Any() with Nullables - 当我期望 True 时返回 False,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5783429/