Linq to Entity - 如何连接条件

Riz*_*Riz 0 c# linq-to-entities

我正在写一个Linq查询.有没有一种方法可以根据一些if条件连接到查询?

就像查询一样

    from res in _db.Person
    where res.Departments.ID == deptId
    select res;
Run Code Online (Sandbox Code Playgroud)

如果我的条件是真的,我希望它是这样的

from res in _db.Person
    where res.Departments.ID == deptId && res.Departments.Type == deptType
    select res;
Run Code Online (Sandbox Code Playgroud)

Jon*_*eet 5

实现"AND"类型条件很容易 - 使用扩展方法语法Where多次调用也更容易:

IQueryable<Person> people = _db.Person
                               .Where(res => res.Departments.ID == deptId);
if (deptType != null)
{
    people = people.Where(res => res.Departments.Type == deptType);
}

// Potentially add projections etc.
Run Code Online (Sandbox Code Playgroud)

编辑:如果你想要"或"功能,它从头开始有点棘手,因为你需要搞乱表达树.我建议你使用这个PredicateBuilder库:

Expression<Func<Person, bool> predicate = res => res.Departments.ID == deptId;
if (deptType != null)
{
    predicate = predicate.Or(res => res.Departments.Type == deptType);
}
IQueryable<Person> people = _db.Person.Where(predicate);
Run Code Online (Sandbox Code Playgroud)