简体   繁体   中英

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:

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.

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. 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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