Method SetFieldAsExpression
- Namespace
- YndigoBlue.Velocity.Model
- Assembly
- YndigoBlue.Velocity.dll
SetFieldAsExpression(ISelectItem, Expression)
Sets a field value to a calculated arithmetic expression.
public void SetFieldAsExpression(ISelectItem selectItem, Expression expression)
Parameters
selectItemISelectItemThe column to set.
expressionExpressionThe expression that will calculate the value.
Examples
Atomically decrement a balance, but only if sufficient funds remain:
// new_balance = balance - 25.00
Expression debit = new Expression();
debit.Add(accountsTable["balance"]);
debit.Add(new ArithmeticOperator(ArithmeticType.Subtract));
debit.Add(new Literal<decimal>(25.00m));
Update update = new Update(accountsTable, [
new Criterion<long>(accountsTable["account_id"], 1234),
new BooleanItem(BooleanType.And),
new Criterion<decimal>(accountsTable["balance"], ConditionalType.GreaterThanOrEqualTo, 25.00m)
]);
update.SetFieldAsExpression("balance", debit);
int rowsUpdated = manager.UpdateRecords(update);
// rowsUpdated == 1 -> debited. rowsUpdated == 0 -> insufficient balance, nothing changed.
// SQL: UPDATE accounts SET balance = (balance - 25.00)
// WHERE account_id = 1234 AND balance >= 25.00
Remarks
Unlike SetFieldAsFunction(ISelectItem, Function), an Expression composes columns, literals and arithmetic operators freely, so the new value can be derived from the row's own current column values.
This makes read-modify-write operations atomic in a single statement — the database performs the arithmetic, so no value is read into the application and written back, which removes the lost-update race that read-then-write is subject to under concurrency. Combine with a WHERE clause guard and the row count returned by UpdateRecords(Update) to implement compare-and-swap semantics.
SetFieldAsExpression(string, Expression)
Sets a field value to a calculated arithmetic expression.
public void SetFieldAsExpression(string fieldName, Expression expression)
Parameters
fieldNamestringThe name of the column to set.
expressionExpressionThe expression that will calculate the value.
Remarks
See SetFieldAsExpression(ISelectItem, Expression) for details and an example.