VB.Net Linq to Entities Null Comparison - 'Is Nothing' or '= Nothing'?

user1359018 picture user1359018 · Jul 10, 2012 · Viewed 14k times · Source

We have several projects in VB.Net, using .Net Framework 4 and Linq to Entities for many of our SQL queries. Moving to EF is a new shift for us (been using it for about 4-6 months) and has the backing of upper management because we can code so much faster. We still use a lot of stored procs, but we even execute those through Linq to Entities as well.

I'm hoping to clear some confusion up and I can't find a direct answer that makes sense. We have some queries where we want records where a specific field has a NULL value. These are simple select queries, no aggregates or left joins, etc. Microsoft recommends the query look something like this MSDN Link:

dim query = from a in MyContext.MyTables
Where a.MyField = Nothing
Select a

I have several projects where I do exactly this and it works great, no warnings in the IDE. Recently a new project was created by another developer and when he did his null check like above, we all get this warning in the IDE:

Warning 1 This expression will always evaluate to Nothing (due to null propagation from the equals operator). To check if the value is null consider using 'Is Nothing'.

Comparing the projects, option explicit and option strict are on for each one. If we ignore the warning, we get the exact record set we are looking for when the app runs. The warning goes away if I change the = sign to IS. But why did this warning appear in one project and not others? It's confusing when even on MSDN there are examples using the equals operator.

Answer

Afshin Gh picture Afshin Gh · Jul 10, 2012

Generated column should be a Nullable(Of T)

So you can check if that field has value or not like this:

dim query = from a in MyContext.MyTables
Where Not a.MyField.HasValue
Select a