Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multiple .Where() clauses on an Entity Framework Queryable

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.

like image 967
Zapnologica Avatar asked Jan 02 '16 03:01

Zapnologica


2 Answers

.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
like image 184
Vlad274 Avatar answered Oct 15 '22 00:10

Vlad274


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.

like image 29
VivekDev Avatar answered Oct 14 '22 23:10

VivekDev