簡體   English   中英

Linq 到實體 - 如何連接條件

[英]Linq to Entity - How to concatenate conditions

我正在寫一個 Linq 查詢。 有沒有一種方法可以根據某些 if 條件連接查詢?

就像查詢一樣

    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;

實現“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.

編輯:如果你想要“或”功能,從頭開始有點棘手,因為你需要弄亂表達式樹。 我建議你使用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);

假設您的條件處於可變條件

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;

或者,您可能希望使用謂詞構建器

我會做這樣的事情:

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

在您嘗試枚舉result之前,查詢不會實際執行,因此您可以根據需要繼續添加條件。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM