gpt4 book ai didi

c# - 将 null 参数传递给 LINQ where 子句

转载 作者:太空宇宙 更新时间:2023-11-03 18:34:00 26 4
gpt4 key购买 nike

我有一个表,其中某些项目可能为空。然后我可以使用这样的查询轻松查询:

db.SomeTable.Where(s => s.SomeCol == null)

很简单,但是当使用恰好为 null 的变量时,这不起作用(没有结果。我怀疑它正在搜索一个空字符串;""),如下所示:

string variable = null;
db.SomeTable.Where(s => s.SomeCol == variable)

我是否必须做一些特别的事情才能让它工作?

最佳答案

使用 LinqPad,您可以看到差异。

前者创建如下查询:

select ...
from SomeTable as t0
where t0.SomeCol IS NULL

而后者是

select ...
from SomeTable as t0
where t0.SomeCol = @p0

相反,您可以在测试中使用 object.Equals。例如,

string test = null;
var q = from c in SomeTable where object.Equals(c.SomeCol, test) select c;

这将根据条件中使用的变量值生成适当的 where 子句。

关于c# - 将 null 参数传递给 LINQ where 子句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18118712/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com