1

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?

7
  • What is the type of SomeCol? Commented Aug 8, 2013 at 5:47
  • 3
    What does "doesn't work" mean? Are you getting a compiler error or an exception? Commented Aug 8, 2013 at 5:48
  • 2
    is this EF of Linq2Sql? If EF, which version? Commented Aug 8, 2013 at 5:50
  • @Heather, I think he need to use DBNull.Value. (just to be more specific) Commented Aug 8, 2013 at 5:50
  • 1
    @Heather I think it's likely that that would not compile. Commented Aug 8, 2013 at 5:51

1 Answer 1

7

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. E.g.,

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.

Sign up to request clarification or add additional context in comments.

1 Comment

If this really is the case then that's yet another case where the abstraction of LINQ to SQL (or EF) is leaky. It's really a pity that there are so many cases, basically making the whole abstraction questionable.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.