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
how about
(x.Show ?? false) == show
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();
}
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With