Multiple .Where() clauses on an Entity Framework Queryable

送分小仙女□ 提交于 2020-01-11 08:34:10

问题


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:


.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



回答2:


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.



来源:https://stackoverflow.com/questions/34562382/multiple-where-clauses-on-an-entity-framework-queryable

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!