简体   繁体   English

将空参数传递给LINQ where子句

[英]Passing null parameters into LINQ where clause

I have a table where some items may be null. 我有一个表,其中某些项目可能为空。 I can query then easily by using a query like so: 我可以使用如下查询轻松查询:

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

Simple enough, but this does not work (No results. I suspect it is searching for an empty string instead; "") when using a variable that happens to be null, like so: 很简单,但是在使用碰巧为null的变量时,这是行不通的(没有结果。我怀疑它正在搜索一个空字符串;“”),如下所示:

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

Do I have to do something special to get this to work? 我需要做一些特别的事情才能使它起作用吗?

Using LinqPad you can see the difference. 使用LinqPad,您可以看到不同之处。

The former creates a query like: 前者创建一个查询,例如:

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

whereas the latter is 而后者是

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

Instead you can use object.Equals in your test. 相反,您可以在测试中使用object.Equals。 Eg, 例如,

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

This will generate the appropriate where clause based on the value of the variable used in the condition. 这将根据条件中使用的变量的值生成适当的where子句。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM