VB.Net Linq to Entities Null Comparison - 'Is

2019-06-22 02:12发布

问题:

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.

回答1:

I believe what you're seeing here is that MyField is a Nullable(Of T) type. Likely a primitive Integer, Single, etc ...

The reason you're seeing this warning is because the compiler promotes the normal equality operator for the primitive type to the Nullable(Of T) version. It essentially executes the following

Dim myField As Integer? = a.MyField
Dim other As Integer? = Nothing
If myField = other Then
 ...
End If

The issue though is that when Integer? has the value Nothing it won't compare equal to anything. Hence the above Where clause will always return False. The compiler is attempting to warn you about this problematic corner of Nullable(Of T) and push you to a Is Nothing check which will determine if a.MyField has a non-null value.

This blog article has a very detailed explanation of why this warning is being generated and all of the mechanics behind it. The article is written for C# but the basic premise is applicable to VB.Net as well.

  • http://blogs.msdn.com/b/abhinaba/archive/2005/12/14/503533.aspx


回答2:

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


回答3:

At least in LINQ to objects you can use this instead:

Nullable(Of Integer).Equals(a, b)

This works fine with both, either or none of the two values being Nothing.