Working around Entity Framework Core's query problem with nullable Boolean values in LINQ queries
Posted: (EET/GMT+2)
In EF Core 2.x, queries involving nullable Boolean properties can sometimes fail to translate correctly to SQL. This usually happens when you mix bool? columns with == true or == false checks.
For example, let's you have the following LINQ query:
var q = db.Users.Where(u => u.IsActive == true);
Depending on the database provider, EF Core may not generate the expected SQL (WHERE IsActive = 1) but instead something that mishandles null values.
The workaround is to use the HasValue and Value properties of nullable types explicitly:
var q = db.Users.Where(u => u.IsActive.HasValue && u.IsActive.Value);
This ensures EF Core translates it cleanly. You can also coalesce the value:
var q = db.Users.Where(u => (u.IsActive ?? false) == true);
Most things in Entity Framework are very intuitive, but some gotchas exist. Keeping this specific pattern in mind avoids unexpected query results.