I have started using the entity framework for a web application and would like to know what the best way would be to allow users to filter lists dynamically.
i.e. If we have a list of people the user can filter by lastname, city, etc.
The problem I am having is that I am using EF 4 with code first and all the fitlering I can find is using Linq queries but I can’t see a way to build up the where clause for the filter dymaically based on the filter options the user has selected. i.e. in SQL you could build,
select * from people, address where lastname = 'jones' and address.city = 'sydney'
Is there a way to build up this list dynamically using linq?
EDIT
The solution I’m going to try will be similar to this Implementing Dynamic Searching Using LINQ. As I prefer to be as generic as possible where I can.
The way to do this is for example defining some type for search criteria:
and define custom extension method for
IQueryable<Person>:Now you only need to create model binder (or use default one if possible) to fill your serach options to
PeopleSearchCriteriainstance and execute simply:If you really want some dynamic approach you can build expression tree manually or check Dynamic Linq (you will lose compile time checks).