Last post Aug 23, 2012 06:32 AM by VimalOnline4U
Apr 20, 2010 04:52 PM|PBecker|LINK
I am trying to build a dynamic LINQ where clause in a search page. The user will have an option for filtering on 1-6 fields. I have read many of the posts, blogs, etc. and I am close...but my "\"" doesn't seem to be working or something else? I included
the DynamicLibrary.cs file and System.Linq.Dynamic reference.
I created a class to store the conditions (fields and values) so that I can build the 'where' clause more easily.
public qryCondition(string _fieldName, string _fieldValue)
FieldName = _fieldName;
FieldValue = _fieldValue;
public string FieldName
public string FieldValue
I verify if there is something in the textbox, dropdown, etc. and add it to my List<qryCondition>.
// load "Where" info List<qryCondition>
List<qryCondition> conditions = new List<qryCondition>();
int index = 0;
index = conditions.Count;
conditions.Add(new qryCondition("\"IncidentNo.Contains(@"+index+")\"","\"" + txtIncidentNbr.Text +"\""));
....do this for all the fields for filtering (~6 fields)
Then I create the "Where" clause that puts the field names with @[Number] parameter holder first, and then add commas with the field valuse separating the parameters.
string qryWhere = "";
string qryParam = "";
foreach (qryCondition q in conditions)
qryWhere += (String.IsNullOrEmpty(qryWhere)?"":"&&") + conditions[conditions.IndexOf(q)].FieldName;
qryParam += (String.IsNullOrEmpty(qryWhere) ? "" : ",") +conditions[conditions.IndexOf(q)].FieldValue;
qryWhere += "," + qryParam;
The end result is when I hard code:
var qryWorks = context.IncidentHeaders.Where("IncidentNo.Contains(@0)", "955").ToList(); --this works
var qry = context.IncidentHeaders.Where(qryWhere).ToList(); --doesn't work
where qryWhere = "IncidentNo.Contains(@0)","955"
The error I receive is:
Expression of type 'Boolean' expected Source =IncidentReporting StackTrace= at System.Linq.Dynamic.ExpressionParser.Parse(Type resultType) in C:\data\vs2k8\DynamicLibrary.cs:line 689
Do you have any idea why this isn't working? What should I do to troubleshoot this? Any help is much appreciated.
ASP.NET Dynamic Data
Apr 20, 2010 10:32 PM|andrewjboyd|LINK
What I do, which is different to what you're doing, but may be worth a go is:
public IQueryable<someTable> SelectAll<TKey>(List<Expression<Func<someTable, bool>>> whereCls)
var selectAllQry = from t in entities.someTable
if (whereCls != null)
foreach(Expression<Func<someTable, bool>> whereStmt in whereCls)
selectAllQry = selectAllQry.Where(whereStmt);
This works a treat. You simply declare a "List<Expression<Func<someTable, bool>>>" and use LINQ to populate the list so it might look like this:
if (txtIncidentNbr.Text.length > 0)
whereCls.Add(t => t.IncidentNo.Contains(txtIncidentNbr.Text);
Apr 21, 2010 02:39 PM|PBecker|LINK
Awesome! That did work and the code is much cleaner. Thank you so much!
Aug 23, 2012 06:32 AM|VimalOnline4U|LINK
Superb! Works perfectly.