4

When I

bool? isApproved = null;
db.Table.Where(item => item.IsApproved == isApproved).Count();

the last line value is 0. But when I

db.Table.Where(item => item.IsApproved == null).Count();

the value is correct.

I'm using SQLite, DbLinq and DbMetal.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Jader Dias
  • 88,211
  • 155
  • 421
  • 625

5 Answers5

2

I have seen it done like this:

 db.Table.Where(
            item => item.IsApproved.HasValue == isApproved.HasValue && 
            (!item.IsApproved.HasValue || item.IsApproved.Value==isApproved.Value ) 
 ).Count();
Nix
  • 57,072
  • 29
  • 149
  • 198
1

Well, I had this problem before, I remember that the problem is in converting the LINQ query to a SQL statement.

The second expression has an equal in SQL that: Where IsAproved is null

but the first expression does not because it is a comparision between a value in the database with a C# nullable variable.

To solve it, I would suggest to try:

db.Table.Where(item => isApproved != null ? item.IsApproved == isApproved.Value 
                                          : item.IsApproved == null).Count();
Homam
  • 23,263
  • 32
  • 111
  • 187
1

See this post

You should use

db.Table.Where(item => item.IsApproved.Equals(isApproved)).Count();

Then you should contact Microsoft and let them know how terrible this behavior is.

Community
  • 1
  • 1
BlueRaja - Danny Pflughoeft
  • 84,206
  • 33
  • 197
  • 283
0

I don't know about the performance hit, but it works

bool? isApproved = null;
db.Table.Where(item => item.IsApproved == isApproved || 
                     !(item.IsApproved.HasValue || isApproved.HasValue))
    .Count();
Jader Dias
  • 88,211
  • 155
  • 421
  • 625
-1

Try :

db.Table.Where(item => item.IsApproved == isApproved.Value).Count();

Alaeddin Hussein
  • 738
  • 1
  • 7
  • 14