1

I'm sorry if this has been asked before, but I looked through the related questions and couldn't find anything pertaining to my situation.

I've got a query that looks like this.

var tempFoo = "";
var foo = tempFoo != "" ? tempFoo : null;

var result = Entities.Where(x => x.Bar == foo);

Bar is a string and a nullable varchar

The problem is that when foo is null the SQL generated by LINQ to SQL is:

([t0].[Bar] = @p0)

where is should be:

([t0].[Bar] IS NULL)

If I substitute foo with null in the expression LINQ to SQL uses the correct IS NULL syntax. Sometimes, however, foo isn't null so I have to use a variable.

So how can I get LINQ to SQL to use IS NULL when foo is null and = when foo is not null ?

PS: The reason for the strange variable assignment is because tempFoo is referencing a named regex capture. If the capture is empty the value is "" so I have to check for an empty value and assign null instead.

Thanks!

1

2 Answers 2

2

There's an article on this topic here: http://blog.linqexchange.com/index.php/how-to-use-is-null-with-linq-to-sql/

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

2 Comments

Thanks! I really thought there would be a more elegant way than using two different expressions but oh well!
The link is dead and the other question mentioned above does not address my issue. The best I can gather from the above comment and the answer below is the need for two different LINQ statements - one if "foo" is null and a second if "foo" is not.
1

As the link that Dan posted, to solve you can use:
var result = Entities.Where(x => ((foo == null && x.Bar == null) || (x.Bar == foo));

It works for me!

Comments

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.