Saving
This event is triggered on the server before saving. The rule is cancelable in order to be able to prevent entities from being saved. You can use this event to update the properties of entities before they are saved.
Note
The entity view validation rules and entity validation rules will be triggered after this rule.
Arguments
You can find the details of the interface on this page
| Name | Type | Description |
|---|---|---|
CreatedItems |
IReadOnlyList<TEntityView> |
The created items. |
ModifiedItems |
IReadOnlyList<TEntityView> |
The modified items. |
CreatedAndModifiedItems |
IReadOnlyList<TEntityView> |
The created and modified items regrouped in the same collection. |
DeletedItems |
IReadOnlyList<TEntityView> |
The deleted items. |
Context |
IBusinessRuleContext |
Represents a key/value pair dictionary that is used to store custom data. You can find the details of the interface on this page |
Cancel |
bool |
If set to true, the save will not be executed. |
Canceling the save operation
Important
For simple validation scenarios, prefer using validation rules instead of canceling the save in a Saving event rule. Validation rules are designed for this purpose and provide better user experience.
Use the Saving event rule to cancel the save operation only when:
- The validation involves multiple items (e.g., checking consistency across a collection)
- The logic is not a pure validation (e.g., an assignment process that may fail)
There are two ways to cancel the save operation from a Saving event rule:
Using BusinessException
You can throw a BusinessException to cancel the save operation. This will display an error message to the user and prevent the save.
/// <inheritdoc/>
public Task OnSavingAsync(ISavingRuleArguments<IServerMethodView> args)
{
foreach (IServerMethodView item in args.CreatedAndModifiedItems)
{
if (string.IsNullOrWhiteSpace(item.Name))
{
throw new BusinessException(Resources.MyModule.NameIsRequired);
}
}
return Task.CompletedTask;
}
Using AddError
Alternatively, you can use the AddError method to report one or more validation errors. This approach has the following advantages:
- Multiple errors: You can report multiple errors in a single save operation.
- Error association: You can explicitly associate an error with a specific entity view instance.
/// <inheritdoc/>
public Task OnSavingAsync(ISavingRuleArguments<IServerMethodView> args)
{
foreach (IServerMethodView item in args.CreatedAndModifiedItems)
{
if (string.IsNullOrWhiteSpace(item.Name))
{
args.AddError(item, Resources.MyModule.NameIsRequired);
}
if (item.Order < 0)
{
args.AddError(item, Resources.MyModule.OrderMustBePositive);
}
}
return Task.CompletedTask;
}
When using AddError, the save operation will be automatically canceled if at least one error has been added.