|
|
Project PageDownloadManualOverviewHello SPF Attributes Constraints Triggers Criteria Child Collections |
OverviewA criteria object defines a set of entities of a certain type. Criteria objects encapsulate how SPF is to retrieve the set of entity IDs that match the criteria. This criteria can be parameterised by having arguments in the criteria constructor. The full code for this tutorial can be found here. Creating CriteriaThere is no restriction on where criteria classes are declared. In this example we will declare the class within the scope of the class to which it relates. With this approach all code relating to the entity remains in the same place: The following declares a criteria object that defines a set of users with a specific user name: public class ByUsername : SpfEntityCriteria { public ByUsername(string p_Username) : base( typeof(User), "SELECT Id FROM tbUsers WHERE Username = {0}", new object[] {p_Username} ) {} } The base constructor takes two or three parameters. The first is always the type of entity in the set and the second parameter is always the SQL that will return a set of matching entity IDs. If this SQL is to be paramterised, as is the case above, then parameters
are denoted by a number in clurly braces and a third parameter must be
provided. This parameter is an object array that contains the values to
be used in the criteria. Using CriteriaWe shall use our new criteria to enforce the constraint that all user names should be unique. As mentioned previously, criteria objects can be used to retrieve and delete sets of objects. In this case all we want to know is if there is at least one match, we don't want the overhead of instantiating any entities: public User() { AddConstraint(new SpfConstraint(UsernameIsUnique), SpfPersistenceAction.Insert); } public SpfBrokenConstraint UsernameIsUnique(ISpfTxnContext p_TxnContext, object p_AppContext) { bool usernameExists = p_TxnContext.RetrieveMatchExists(p_AppContext, new User.ByUsername(this.Username)); if (usernameExists) { return new SpfBrokenConstraint("The username " + this.Username + " is not unique", "Username"); } else { return null; } } The constraint uses the current transaction context to see if there are
any users that have the same name. If there is such a uset then we return
a broken constraint saying what was wrong. SummaryWe have seen how to create and use criteria objects. The example showed how they can be created within the same class to which they relate, thereby keeping all relevant code together. We also saw how criteria objects can be used to implement a constraint. |