2
Dim records = From record In db.table
              Where record.Level = "Level 1"
              Where record.NewNumber IsNot Nothing
              Select record.Number

When I call records.ToString() I get an output like so:

SELECT [Extent1].[Number] AS [Number] FROM [dbo].[table] AS [Extent1] WHERE [Extent1].[Level] = @p__linq__0

The where clause for NewNumber is not null is missing. If I change the linq to where NewNumber is nothing I get the following:

SELECT CAST(NULL AS varchar(1)) AS [C1] FROM ( SELECT 1 AS X ) AS [SingleRowTable1] WHERE 1 = 0

What is going on here? The number field is my primary key and newnumber is just another field. I've only changed some of the names/values for this post. Executing both where clauses on the same line with And/AndAlso makes no difference.

The field NewNumber is configured as such.

[Property](Function(x) x.NewNumber).HasMaxLength(20).HasColumnName("Newnumber").IsOptional()

2
  • AndAlso instead of the second Where ? Commented Mar 28, 2018 at 14:53
  • No difference unfortunately. Commented Mar 28, 2018 at 14:55

1 Answer 1

1

EF knows that NewNumber can't be null/nothing and either ignores the predicate (IsNot Nothing) because it's always true, or when it's always false (Is Nothing) it turns it into something that's easier to evaluate for the query optimizer.

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

9 Comments

Newnumber is a nullable nvarchar(20) so it shouldn't be optimizing like this.
Well, EF doesn't know it's nullable. It's probably mapped as required.
I thought the same right after I posted that and explicitly marked it as optional with no change to the SQL. Tho it says in the description that string properties are nullable by default.
Just to exclude the odd case: you do add the configuration class to the modelBuilder, do you?
Definitely the field is required from EF point of view. OP has to find why. Since string is optional by default, either data type is different, or the field is FK for required relationship etc.
|

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.