Microsoft provides example like the one I have copied below for creating multiple conditions for a QueryExpression. Is there way to structure a QueryExpression so that you could dynamically handle a unknown number of conditions? In Microsofts example below they use condition1, condition2 and so on... Again I'm wondering if there's a way to create a more reusable QueryExpression that can handle a variable number of conditions. I know the whole thing could be done in LINQ but I'm specifically trying to determine if it could be done with QueryExpression.
// Create the query expression and set the entity to contact.
QueryExpression query = new QueryExpression();
query.EntityName = "contact";
// Create a condition where the first name equals Joe.
ConditionExpression condition1 = new ConditionExpression();
condition1.AttributeName = "firstname";
condition1.Operator = ConditionOperator.Equal;
condition1.Values = new string[] { "Joe" };
// Create another condition where the first name equals John.
ConditionExpression condition2 = new ConditionExpression();
condition2 .AttributeName = "firstname";
condition2 .Operator = ConditionOperator.Equal;
condition2 .Values = new string[] { "John" };
So you could programmatically build QueryExpressions, which might help to streamline object creation. The only issue I would raise, is that you may find your queries are so different it is difficult to create generic functions to support them all.
In any case here is a simple example which should hopefully get you started.
public static QueryExpression BuildQueryExpression(String entityName, ColumnSet columnSet, LogicalOperator logicalOperator, List<ConditionExpression> conditions)
{
QueryExpression query = new QueryExpression(entityName);
query.ColumnSet = columnSet;
query.Criteria = new FilterExpression(logicalOperator);
conditions.ForEach(c => query.Criteria.AddCondition(c));
return query;
}
Usage:
QueryExpression query = BuildQueryExpression("contact", new ColumnSet(true), LogicalOperator.And, new List<ConditionExpression>()
{
new ConditionExpression("firstname", ConditionOperator.Equal, "James" ),
new ConditionExpression("lastname", ConditionOperator.Equal, "Wood" ),
});
I know this is an old question, but I'd finally found and elegant way of writing QueryExpression, and thought would be good to share with the community.
The same query could be written like so:
FilterExpression _filter = new FilterExpression(LogicalOperator.And);
_filter.AddCondition("firstname", ConditionOperator.Equal, "Joe");
_filter.AddCondition("firstname", ConditionOperator.Equal, "John");
dynamic _queryExpression = new QueryExpression {
EntityName = Contact.EntityLogicalName,
ColumnSet = new ColumnSet(true),
Criteria = _filter
};
LinqKit's PredicateBuilder provides a set of clean extensions to manage this type of problem.