I’m trying to convert some old code that directly builds SQL queries to Entity Framework, and came across a problem that many seem to have (judging from the large number of questions surround that topic): how to express dynamic where conditions in linq.
How could I express the following code with a linq query:
switch (status) {
case "0":
sqlwhere = " WHERE status < 0 ";
break;
case "-1":
sqlwhere = " WHERE status = -1 ";
break;
case "-100":
sqlwhere = " WHERE status = -100 ";
break;
case "1":
default:
sqlwhere = " WHERE status >= 0 ";
break;
}
if (strsearch != "")
sqlwhere += " AND desc LIKE '%" + strsearch + "%' ";
string sqlc = "SELECT top 10 * FROM c " + sqlwhere + " order by date desc";
I’ve read about PredicateBuilder and the dynamic Linq extensions in other posts, but I think that a simple case like could be solvable without external libraries.
Using .net 4.5, EF 5.0, C#, can this be done in a “dynamic” way without building the complete linq statement for each single case?
If you don’t want to use something external, then simply use fluent API:
BTW You can create extension method for filtering by status. And your query will look like:
Extension method: