Last post Sep 21, 2016 04:51 PM by bchernick
Sep 19, 2016 08:09 PM|bchernick|LINK
Just wondering. Is it possible to set up conditional checks in the Where statement of a data context call?
I ask because I may have to set up a program to allow the user to select which field he wants to filter by.
Something like this:
int xx = 1;
.Where( f => ( xx == 1 ? f.CreatedDate >= sDate && f.CreatedDate <= eDate :f.ModifiedDate >= sDate && f.ModifiedDate <= eDate )).Select (....
This compiled ok but seemed to hang.
Sep 19, 2016 09:09 PM|deepalgorithm|LINK
Yes it is possible. You basically build your query first then defer execution until after its built by calling ToList().
Have a look at the following SO posts:
Another option may be to use PredicateBuilder which is part of LINQKit. It will allow you to chain together some calls to Where.
There are plenty of examples online on its usage with Entity Framework queries.
Sep 20, 2016 06:40 AM|Nan Yu|LINK
Hi bchernick ,
LINQ to Entity queries return IQueryable, so you can build your query in pieces:
IQueryable<Person> query = context.People;
if (Country != "All")
query = query.Where(p => p.Country == Country);
List<Person> fetchedPeople = query.ToList();
At the end, when you execute the fetchedPeople query , EF will consolidate all of those smaller Where clauses into a single SQL query to run against your data.
Sep 21, 2016 04:51 PM|bchernick|LINK
Message removed. (Spoke too soon.)