有没有一种更优雅的方法可以在实体框架核心支持的Linq查询中具有多个OR条件



我正在编写一个查询,根据用户提供的输入,我需要添加"析取"条件(也就是说"或"条件(。要用"联合"条件("one_answers"条件"(来做这件事,这是相当直接的…

var employees = repository.GetAll<Employee>(); // returns IQueryable
if (!string.IsNullOrEmpty(firstName))
employees = employees.Where(e => e.FirstName.Contains(firstName));
if (!string.IsNullOrEmpty(lastName))
employees = employees.Where(e => e.LastName.Contains(lastName));
if (!string.IsNullOrEmpty(email))
employees = employees.Where(e => e.Email.Contains(email));

根据是否填充firstName、lastName或电子邮件,生成的查询将具有0到3个AND条件。但是,有没有一种方法可以使用OR条件来实现这一点?例如,是否有以下内容。。。

// Notice these use of OrWhere which does not exist...
var employees = repository.GetAll<Employee>(); // returns IQueryable
if (!string.IsNullOrEmpty(firstName))
employees = employees.OrWhere(e => e.FirstName.Contains(firstName));
if (!string.IsNullOrEmpty(lastName))
employees = employees.Orwhere(e => e.LastName.Contains(lastName));
if (!string.IsNullOrEmpty(email))
employees = employees.OrWhere(e => e.Email.Contains(email));

我知道我可以做一个很大的条件。。。

var employees = repository.GetAll<Employee>().Where(e =>
(!string.IsNullOrEmpty(firstName) && e.FirstName.Contains(firstName)) ||
(!string.IsNullOrEmpty(lastName) && e.LastName.Contains(lastName)) ||
(!string.IsNullOrEmpty(email) && e.Email.Contains(email))
);

但是生成的查询效率不高,代码在我看来也不那么优雅。我希望有一种更好的方法可以做到这一点,看起来更像第二个例子。

如果你想要的是在null检查和属性过滤器之间使用OR条件,这里有一种方法。。。

var employees = repository.GetAll<Employee>(); // returns IQueryable
employees = employees.Where(e => 
(firstName == null || e.FirstName.Contains(firstName)) && 
(lastName == null || e.LastName.Contains(lastName)) &&
(email == null || e.Email.Contains(email)));

最新更新