Multiple .Where() clauses on an Entity Framework Q

2019-02-22 10:34发布

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.

2条回答
够拽才男人
2楼-- · 2019-02-22 11:05

.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
查看更多
戒情不戒烟
3楼-- · 2019-02-22 11:15

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.

查看更多
登录 后发表回答