Simplified Criteria Syntax
- 3 minutes to read
#Regular Criteria Syntax
The common ways of building criteria are:
Creating criteria in code as objects.
Using the static CriteriaOperator.Parse method.
Both approaches are not type-safe. In the second approach, the whole string that contains the query expression can’t be checked, and therefore can bring up runtime errors.
#Simplified Criteria Syntax
The DevExpress Data Library features the simplified criteria syntax. You can rewrite the criterion in the example above like this:
The simplified criteria syntax supports the following operators: ==
, !=
, >
, <
, >=
, <=
, +
, -
, *
, /
, %
, !
, &
and |
. For technical reasons, we suggest you use the single &
and |
operators instead of &&
or ||
.
The simplified expressions can be used in all the places where you can otherwise pass CriteriaOperator instances. For example, you can pass them to an XPCollection<T> constructor as shown below.
XPCollection<Person> coll = new XPCollection<Person>(session,
Person.Fields.Name == "Winny" & Person.Fields.Age > 30);
The operator overload for Boolean types cannot be implemented. In this case, explicitly cast Boolean literals as shown below.
// bool isAdmin;
CriteriaOperator filter =
(Person.Fields.IsAdmin == new OperandValue(isAdmin) & Person.Fields.Status != "INACTIVE");
// or
// CriteriaOperator filter =
// (Person.Fields.IsAdmin == (CriteriaOperator)isAdmin & Person.Fields.Status != "INACTIVE");
#How This Works
The DevExpress Data Library exploits operator overloading to allow for the == operator (= in Visual Basic) to be used in this scenario. The expression on the left hand-side has to be of the OperandProperty type for this to work. So you can use the following code snippet to get the same result.
OperandProperty prop = new OperandProperty("Name");
CriteriaOperator op = prop == "Winny";
// CriteriaOperator op = new BinaryOperator("Name", "Winny");
To simplify things, you can extend a persistent class with a nested class (called Fields in the code examples above) to expose persistent properties as property operands. So, the persistent class MyPersistentClass we used previously should look like this:
using DevExpress.Data.Filtering;
// ...
public class MyPersistentClass: XPObject {
public MyPersistentClass(Session session): base(session) { }
public string Name {
get { return GetPropertyValue<string>(nameof(Name)); }
set { SetPropertyValue<string>(nameof(Name), value); }
}
public new class Fields {
private Fields() { }
public static OperandProperty Name {
get { return new OperandProperty("Name"); }
}
}
}