2011-07-21 57 views
0

我在写一个Linq查询。有没有一种方法可以连接到基于某些条件进行查询?Linq to Entity - 如何连接条件

像查询

from res in _db.Person 
    where res.Departments.ID == deptId 
    select res; 

而且如果我有真正的一个条件,我想它是这样的

from res in _db.Person 
    where res.Departments.ID == deptId && res.Departments.Type == deptType 
    select res; 
+0

能否请你澄清你所需要的逻辑,你已经声明你需要或者在另一个评论你需要或? –

+0

使用这种方法http://stackoverflow.com/questions/21512230/where-clause-with-multiple-unknown-conditions –

回答

3

假设你的条件是在变工况

from res in _db.Person 
where res.Departments.ID == deptId && (!condition || res.Departments.Type == deptType) 
select res; 

版本,不含或要求

from res in _db.Person 
where res.Departments.ID == deptId || (condition && res.Departments.Type == deptType)) 
select res; 

另外,你不妨用predicate builder

5

实现一个“和”类型的条件很简单 - 更轻松使用扩展方法语法多次调用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. 

编辑:如果你想要“或”功能,从头开始有点棘手,因为你需要搞乱表达式树。我建议你使用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); 
+0

我认为这将是第一在哪里和第二在哪里 - 对吗? 我需要OR – Riz

+0

@eFriend:如果您需要OR,您为什么在您的问题中有AND? OR很难实现。 –

+0

是我的错,很抱歉。你能建议OR实施吗? – Riz

1

我会做这样的事情:

var result = _db.Person.Where(x=>x.Departments.ID == deptId); 
if(myCondition) 
    result = result.Where(x=>x.Departments.Type == deptType); 

并没有真正执行查询,直到你试图枚举result,这样你就可以不断加入的条件,只要随你便。

+0

我认为这将是First-Where和Second-Where--对吗? 我需要OR – Riz