Multiple .Where() clauses on an Entity Framework Queryable

c# entity-framework entity-framework-6

Question

I am trying to implement a complex filter using Entity Framework: I want to add where clauses to the queryable object based on my provided search criteria.

Can I do the following in Entity Framework 6?

var queryable = db.Users.Where(x => x.Enabled && !x.Deleted);
// Filter
var userId = User.Identity.GetUserId();
queryable.Where(x => x.AspNetUser.Id == userId);
queryable.Where(x => x.Status >= 2); 
// ...etc

I know that I can do:

var queryable = db.Users
 .Where(x => x.Enabled && !x.Deleted)
 .Where(x => x.AspNetUser.Id == userId)
 .Where(x => x.Status >= 2); 

But I am not getting the expected results with this solution. It seems to be ignoring the seconds two where clauses.

1
6
1/2/2016 3:50:36 AM

Accepted Answer

.Where returns a queryable, it does not modify the original. So you just need to save the new queryable.

var queryable = db.Users.Where(x => x.Enabled && !x.Deleted);
// Filter
var userId = User.Identity.GetUserId();
queryable = queryable.Where(x => x.AspNetUser.Id == userId);
queryable = queryable.Where(x => x.Status >= 2); 
// ...etc
7
1/2/2016 3:54:26 AM

Popular Answer

I guess what you are trying is runtime search. If that is the case you have two options.

  1. Using expressions to build a run time where clause. You may have to use a predicate builder. This predicate builder may not work with Entity Framework. But this one should work with entity framework.

  2. Using Dynamic Linq. This by far the easiest. Its very versatile. Not only can you do Where, it supports select and order by and others as well runtime quite easily!!! Do take a look.



Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow