C# Lambda在bool-where子句中将null视为false
我有以下实体框架lambda查询:C# Lambda在bool-where子句中将null视为false,c#,C#,我有以下实体框架lambda查询: public IList<MyClass> GetMyClass(int id, bool show) { using (var ctx = new DbContext()) { return ctx.MyClasses.Where(x => x.Id == id && x.Show == s
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();
}
}
目前,如果我向下传递False
,空值将被排除,我需要将它们归类为False
我无法更改数据库以下代码应在
Show==True
时返回Show==True的记录,在Show==False
时返回Show==False或NULL的记录
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();
}
}
}
private void Repeat(对象状态)
{
公共IList GetMyClass(int-id,bool-show)
{
使用(var ctx=new DbContext())
{
返回ctx.MyClasses.Where(x=>
x、 Id==Id&&
(x.Show==Show | |!Show&&x.Show==null)
.OrderByDescending(x=>x.CreationDate).Take(100).ToList();
}
}
}
怎么样
(x.Show ?? false) == show
只是另一种思考表达式的方式。在LINQ to实体中不是一个好的实践
(x.Show == true) == show
这是我们能写的最好的C代码,但它会被翻译成丑陋的CASE语句。我做了一次搜索,没有找到合并的方法。我想做“x.Show.GetValueOrDefault()==Show”,但它不会编译
(x.Show == true) == show