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.
When you compare
trueto your.IsEnabledfield, LINQ to SQL passes thetrueas a parameter in the query. The problem with that is that the translation will returnNULL:Because of how SQL92 defines how comparing to NULL works, both
WHENconditions are false.It is explained in this this blog post [Disclaimer: the post is mine]
Use
Enabled = NxEnabled ?? falseinstead as a work-around.