2011-07-21 58 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