Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is this query throwing an exception?

Tags:

c#

linq-to-sql

I have a User table that has a BIT NULL column called NxEnabled, and I can't change. Some of the records actually contain a NULL in that column.

I don't want to have a Nullable in C#, so it makes sense comparing it to true in the projection (the code is simplified, but this generates the same error):

context.Users.Where(x => x.Id == 4)
             .Select(x => new 
                  { 
                      Id = x.Id,
                      Name = x.Name,
                      Enabled = x.NxEnabled == true
                  });

Why does this query throw an

InvalidOperationException: The null value cannot be assigned to a member with type System.Boolean which is a non-nullable value type.`

when enumerated?

edit: Sorry for the typo. The query was actually more complex but the where clause is not the problem.

like image 656
Alessandro D'Amario Avatar asked Jan 14 '13 21:01

Alessandro D'Amario


2 Answers

When you compare true to your .IsEnabled field, LINQ to SQL passes the true as a parameter in the query. The problem with that is that the translation will return NULL:

SELECT [t0].[Id], [t0].[Name],
    (CASE 
        WHEN [t0].[NxEnabled] = @p0 THEN 1
        WHEN NOT ([t0].[NxEnabled] = @p0) THEN 0
        ELSE NULL
     END) AS [Enabled]
FROM [Users] AS [t0]

Because of how SQL92 defines how comparing to NULL works, both WHEN conditions are false. It is explained in this this blog post [Disclaimer: the post is mine]

Use Enabled = NxEnabled ?? false instead as a work-around.

like image 134
istepaniuk Avatar answered Oct 04 '22 08:10

istepaniuk


Typo -- you need the double-equals ==:

.Where(x => x.Id == 4)
like image 29
McGarnagle Avatar answered Oct 04 '22 10:10

McGarnagle