比较表达式<func <t,bool =“”>&gt;在查询中bool

时间:2017-09-26 09:11:05

标签: c# entity-framework lambda

您如何在实体框架查询中将Expression<Func<T, bool>>bool进行比较?

这是我想要做的一个例子:

Expression<Func<Errand, bool>> isClosed = (x)
    => x.ClosedDate.HasValue;

bool input = false;

var model = db.Errands
    .Where(isClosed == input) // comparing to just boolean is not valid
    .ToList();

你怎么能实现这个目标?

1 个答案:

答案 0 :(得分:2)

一种选择是使用方法动态创建表达式:

public Expression<Func<Errand, bool>> IsClosed(bool closed)
{
    return x => x.ClosedDate.HasValue == closed;
}

并像这样使用它:

bool input = false;

var model = db.Errands
    .Where(IsClosed(input))
    .ToList();