|
|
Project PageDownloadManualOverviewHello SPF Attributes Constraints Triggers Criteria Child Collections |
OverviewFor an entity to be saved to a data store all its fields must contain valid values and all constraints on the object must hold. A constraint is any method that implements the signature defined by the SpfConstraint delegate shown below: public delegate SpfBrokenConstraint SpfConstraint(ISpfTxnContext p_TxnContext, object p_AppContext); The full code for this tutorial can be found here. Creating ConstraintsContinuing the user example from the attributes tutorial, if we wanted to ensure that the password entered matched the confirmation password then we would need to create a method with a signature matching SpfConstraint, i.e.: public SpfBrokenConstraint PasswordIsConfirmed(ISpfTxnContext p_TxnContext, object p_AppContext) { The first parameter is the current transaction context. This is created by SPF when an method is invoked on a broker and is passed through to all business logic. It provides the methods to intereact with the data store and any interactions are automatically enlisted in the current transaction. The second parameter is an application specific object that is passed through from the code which invoked the broker method. This can be used to store application specific context information, e.g. the current user, session ID etc. Next we need to code the test we wish to perform: if (this.Password == this.PasswordConfirmation) { return null; } else { return new SpfBrokenConstraint("Password and confirmation do not match"}); } As you can see, the two password values are compared and null is returned if they are equal. This indicates that the constraint holds. If the two password values are not equal then a new broken constraint object is returned containing an explanatory message. Adding ConstraintsTo ensure the constraint is called, it must be added to the entity's set of constraints via the AddConstraint method on the SpfEntity base class. This is done in the constructor as follows: public User() { AddConstraint(new SpfConstraint(PasswordIsConfirmed)); } Now an SpfValidation exception will occur when an attempt is made to save the user and the password fields do not match. Conditional ConstraintsBy default a constraint will be checked when an entity is inserted or updated. This is not always the required behaviour. For eaxmple, say we wanted to check that a username was not taken. This only applies when an entity is being inserted, as it would be true for an update if the username was not changed. This can be done by specifying the conditions using the SpfPersistenceAction flags, e.g.: AddConstraint(new SpfConstraint(UsernameIsUnique), SpfPersistenceAction.Insert); SummaryWe have seen how we can create constraints within the entity class and how to add them so SPF will check them when an entity is persisted. In addition, we also saw how we can tell SPF when a constraint should be checked. |