I am trying to convert some old code that directly builds SQL queries into the Entity Framework, and ran into a problem that many seem to have (judging by the large number of questions surrounding this topic): how to express dynamics when conditions are in linq .
How can I express the following code with a linq request:
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 read about PredicateBuilder and Linq dynamic extensions in other posts, but I think a simple case is kind of solvable without external libraries.
Using .net 4.5, EF 5.0, C #, can this be done in a "dynamic" way without creating a complete linq statement for each individual case?
source share