Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Lambda treating null as false in bool where clause

Tags:

c#

I have the following Entity Framework lambda query:

public IList<MyClass> GetMyClass(int id, bool show)
{
    using (var ctx = new DbContext())
    {
        return ctx.MyClasses.Where(x =>
               x.Id == id &&                      
               x.Show == show // <-- nullable bool
               .OrderByDescending(x => x.CreationDate).Take(100).ToList();
    }
}

My front end view has passed the show boolean down indicating the users preference for what to return.

In the database, the show property is nullable.

This is a very heavy query, so I have limited it to 100 at a time, thousands of rows are null, thousands are true and thousands are false.

Question

How can I say, without making the query inefficient, psuedo code:

.Where(x => x.Show == show) (where null or false == false)

As it stands, if I pass False down, the nulls are excluded, and I need them to be classed as False.

I cannot change the database

like image 779
JsonStatham Avatar asked Dec 17 '22 21:12

JsonStatham


2 Answers

how about

(x.Show ?? false) == show
like image 199
Z.D. Avatar answered Jan 04 '23 22:01

Z.D.


The following code should return records with Show == True when show == true, and records with Show == False or NULL when show == false

private void Repeat(object state)
{
    public IList<MyClass> GetMyClass(int id, bool show)
    {
        using (var ctx = new DbContext())
        {
            return ctx.MyClasses.Where(x =>
                   x.Id == id &&
                   (x.Show == show || !show && x.Show == null)
                   .OrderByDescending(x => x.CreationDate).Take(100).ToList();
        }
    }
}
like image 24
Mel Gerats Avatar answered Jan 04 '23 21:01

Mel Gerats