首页 > 解决方案 > Lambda 在 bool where 子句中将 null 视为 false

问题描述

我有以下实体框架 lambda 查询:

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();
    }
}

我的前端视图传递了show布尔值,指示用户对返回内容的偏好。

在数据库中,show属性是nullable

这是一个非常繁重的查询,所以我一次将其限制为 100 个,数千行是null,数千行是 ,数千行truefalse

问题

我怎么能说,而不使查询效率低下,伪代码:

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

就目前而言,如果我传递False下去,则将排除空值,并且我需要将它们归类为 False。

我无法更改数据库

标签: c#

解决方案


怎么样

(x.Show ?? false) == show

推荐阅读