开发者

Linq to Entity - How to concatenate conditions

I am writing a Linq Query. Is there a way that I can concatenate to query based on some if conditions?

Like on query is

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

And if I have a condition true, I would like it t开发者_JAVA技巧o be something like

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


Implementing an "AND" type condition is easy - and easier using extension method syntax to call Where multiple times:

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.

EDIT: If you want "OR" functionality, it's slightly tricky from scratch, as you need to mess around with expression trees. I suggest you use the PredicateBuilder library:

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);


Assuming your condition is in the variable condition

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

Version that does or as requested

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

Alternatively you may wish to use predicate builder


I would do something like this:

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

The query is not actually executed until you attempt to enumerate result, so you can keep adding conditions as long as you like.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜